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