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 with Closure INPUT n = 10 (starting value) createCounter(n) let count = n return () => count++ Function Calls: call 1 call 2 call 3 ALGORITHM STEPS 1 Create Closure Initialize count = n (10) 2 Return Arrow Func () => count++ 3 First Call Returns 10, count = 11 4 Subsequent Calls Return current, increment Closure State Changes count=10 ret: 10 --> count=11 ret: 11 --> count=12 ret: 12 FINAL RESULT Output Array 10 11 12 [0] [1] [2] [10, 11, 12] OK - Success! Each call returns current value then increments the closed-over count const counter = createCounter(10) counter() // 10, 11, 12... Key Insight: Arrow functions capture variables from their surrounding scope (closure). The inner function remembers and has access to 'count' even after createCounter() has finished executing. The post-increment (count++) returns current value THEN increments for next call. TutorialsPoint - Counter | Arrow Function Closure Approach
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