NeetCode #945LC-2620EasyJavaScript
← Back to All Problems

#945 · #2620 · Counter(计数器)

📌 Problem Statement & Constraints

Given an integer n, return a counter function. The first call returns n, and every subsequent call returns one more than the previous. Constraints: -1000 <= n <= 1000, at most 1000 calls.

💡 Core Algorithmic Approaches

  1. Use a closure to hold mutable state: the local variable n is captured by the inner function and survives between calls.
  2. Each call runs n++ (post-increment), which returns the old value and then increments — exactly the required behaviour.
  3. Do not use ++n, which increments first and would make the first call return n + 1.
  4. This is the classic demonstration of functional state: no class and no global variable is needed.

💻 Benchmark Python3 Implementation

var createCounter = function(n) {
    // The closure captures n; n++ returns the old value then increments
    return function() {
        return n++;
    };
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1): every call is constant time.
💾 Space Complexity
O(1): the closure captures a single integer.

⚠️ Interview Pitfalls & Follow-ups

  • Using ++n: the first call would return n + 1 instead of n.
  • Declaring n as a global: multiple counters would then interfere with each other.
  • Recomputing from a separate call count: extra state is unnecessary; a closure increment is simpler.