Counter - 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).

The counter function should maintain its internal state between calls and increment the value each time it's invoked.

Input & Output

Example 1 — Positive Counter
$ Input: n = 10
Output: [10, 11, 12]
💡 Note: counter() returns 10, then counter() returns 11, then counter() returns 12. Each call increments the internal state.
Example 2 — Negative Counter
$ Input: n = -2
Output: [-2, -1, 0]
💡 Note: counter() returns -2, then counter() returns -1, then counter() returns 0. Works with negative starting values.
Example 3 — Zero Counter
$ Input: n = 0
Output: [0, 1, 2]
💡 Note: counter() returns 0, then counter() returns 1, then counter() returns 2. Starting from zero and incrementing normally.

Constraints

  • -1000 ≤ n ≤ 1000
  • At most 1000 calls will be made to counter()

Visualization

Tap to expand
Counter Function: State Management with ClosuresInputn = 10createCounter(10)returns functioncounter()→ 10counter()→ 11counter()→ 12Internal staten = 13Closure preserves state: n increments after each returnResult: [10, 11, 12] with internal state n = 13
Understanding the Visualization
1
Input
Initial value n = 10
2
Process
Create counter function using closure
3
Output
Each call returns current value then increments
Key Takeaway
🎯 Key Insight: Closures allow functions to remember and modify variables from their creation scope, enabling persistent state between calls
Asked in
Google 15 Meta 12 Amazon 8
98.0K Views
High Frequency
~5 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen