
Sponsored
Sponsored
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.
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.
1function createCounter(init) {
2 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.
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.
Time Complexity: O(1) per operation.
Space Complexity: O(1) as the counter uses a fixed amount of memory.
1public class Counter {
2 private int current;
3 private readonly int initial;
4
5 public Counter(int init) {
6 current = init;
7 initial = init;
8 }
9
10 public int Increment() {
11 return ++current;
12 }
13
14 public int Decrement() {
15 return --current;
16 }
17
18 public int Reset() {
19 current = initial;
20 return current;
21 }
22}
23
24public class CounterFactory {
25 public static Counter CreateCounter(int init) {
26 return new Counter(init);
27 }
28}In C#, we define a Counter class with methods for incrementing, decrementing, and resetting the value. A factory method in CounterFactory is used to instantiate the class.