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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code