Problem

Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).

Examples

Example 1

1
2
3
4
5
6
7
Input: 
n = 10 
["call","call","call"]
Output: [10,11,12]
Explanation: counter() = 10 // The first time counter() is called, it returns n.
counter() = 11 // Returns 1 more than the previous time.
counter() = 12 // Returns 1 more than the previous time.

Example 2

1
2
3
4
5
Input: 
n = -2
["call","call","call","call","call"]
Output: [-2,-1,0,1,2]
Explanation: counter() initially returns -2. Then increases after each sebsequent call.

Constraints

  • -1000 <= n <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] === "call"

Solution

Method 1 – Closure (Stateful Function)

Intuition

The key idea is to use a closure to capture the current value of the counter. Each time the returned function is called, it increments and returns the value, maintaining state between calls.

Approach

  1. Define a function createCounter that takes an integer n.
  2. Inside, define and return a function that:
    • Returns the current value.
    • Increments the value for the next call.
  3. The closure ensures the value persists across calls.

Code

1
2
3
4
5
6
function createCounter(n) {
    let ans = n;
    return function() {
        return ans++;
    };
}
1
2
3
4
5
6
function createCounter(n: number): () => number {
    let ans = n;
    return function(): number {
        return ans++;
    };
}

Complexity

  • ⏰ Time complexity: O(1), each call returns and increments a number in constant time.
  • 🧺 Space complexity: O(1), only a single variable is stored in the closure.