Counter II - Problem

Write a function createCounter that accepts an initial integer init and returns an object with three functions.

The three functions are:

  • increment() increases the current value by 1 and then returns it.
  • decrement() reduces the current value by 1 and then returns it.
  • reset() sets the current value to init and then returns it.

Input & Output

Example 1 — Basic Counter Operations
$ Input: init = 5, calls = ["increment", "increment", "decrement", "reset", "reset"]
Output: [6,7,6,5,5]
💡 Note: Starting with 5: increment() → 6, increment() → 7, decrement() → 6, reset() → 5, reset() → 5
Example 2 — Starting from Zero
$ Input: init = 0, calls = ["increment", "decrement", "reset"]
Output: [1,-1,0]
💡 Note: Starting with 0: increment() → 1, decrement() → 0, then decrement() → -1, reset() → 0
Example 3 — Negative Initial Value
$ Input: init = -2, calls = ["reset", "increment", "decrement"]
Output: [-2,-1,-2]
💡 Note: Starting with -2: reset() → -2, increment() → -1, decrement() → -2

Constraints

  • -1000 ≤ init ≤ 1000
  • At most 1000 calls will be made to increment, decrement and reset

Visualization

Tap to expand
Counter II: State Management ProblemInputinit = 5calls: [increment,increment, decrement,reset, reset]Counter Objectincrement(): current + 1decrement(): current - 1reset(): current = initOutput[6,7,6,5,5]Array of returnvalues from eachmethod callState persists across method calls: 5 → 6 → 7 → 6 → 5 → 5💡 Closures or classes maintain private state between function invocations
Understanding the Visualization
1
Input
Initial value init=5 and sequence of method calls
2
Process
Counter object tracks current value and responds to increment/decrement/reset
3
Output
Array of return values from each method call
Key Takeaway
🎯 Key Insight: Use closures or classes to create persistent state between method calls
Asked in
Google 15 Facebook 12
23.4K Views
Medium Frequency
~10 min Avg. Time
876 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