Problem Description
Design a counter object that supports three operations: increment, decrement, and reset. The counter is initialized with a given starting value, and each method update returns the new counter value.
Key Insights
- Maintain a current counter value that initially equals the given starting value.
- The increment function increases the counter by 1.
- The decrement function decreases the counter by 1.
- The reset function sets the counter back to its original initialization value.
- No advanced data structures are needed; a simple variable closure or object state suffices.
Space and Time Complexity
Time Complexity: O(1) for each operation. Space Complexity: O(1) as only a few variables are maintained regardless of input size.
Solution
We can solve this problem by creating a closure (or an object) that encapsulates the current state of the counter along with the initial value. Each provided method (increment, decrement, reset) will access and update this state. The primary trick is to ensure that the reset function always brings back the counter to the original initialization value provided to the createCounter function.