Write a function createCounter. It should accept an initial integer init. It should return 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.
Example 1:
Input: init = 5, calls = ["increment","reset","decrement"] Output: [6,5,4] Explanation: const counter = createCounter(5); counter.increment(); // 6 counter.reset(); // 5 counter.decrement(); // 4
Example 2:
Input: init = 0, calls = ["increment","increment","decrement","reset","reset"] Output: [1,2,1,0,0] Explanation: const counter = createCounter(0); counter.increment(); // 1 counter.increment(); // 2 counter.decrement(); // 1 counter.reset(); // 0 counter.reset(); // 0
Constraints:
-1000 <= init <= 10000 <= calls.length <= 1000calls[i] is one of "increment", "decrement" and "reset"This approach uses closure to maintain the state of the counter. We create an outer function that returns three inner functions: increment, decrement, and reset. These functions have access to the outer function's scope where the initial state and current state are maintained.
The createCounter function accepts an initial value and returns an object containing three methods. The current variable is enclosed within the returned object, allowing each of the methods to manipulate the state properly. The increment method increases the counter, the decrement method decreases it, and the reset method restores it to its initial value.
Python
Time Complexity: O(1) for each operation since they perform a constant amount of work.
Space Complexity: O(1), only a few variables are used to hold the state.
This approach involves creating a class outside the function that models the counter with methods for incrementing, decrementing, and resetting. An instance of this class is created and returned by the createCounter function.
A Java class named Counter is defined with private fields to hold the current and initial values. Its methods implement the required functionalities. The CounterFactory class provides a static method to create a counter instance.
C#
Time Complexity: O(1) per operation.
Space Complexity: O(1) as the counter uses a fixed amount of memory.
| Approach | Complexity |
|---|---|
| Closure-Based Counter | Time Complexity: O(1) for each operation since they perform a constant amount of work. |
| Class-Based Counter Object | Time Complexity: O(1) per operation. |
LeetCode was HARD until I Learned these 15 Patterns • Ashish Pratap Singh • 1,002,262 views views
Watch 9 more video solutions →Practice Counter II with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor