
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.
1def createCounter(init):
2 class
In this Python solution, we define a class Counter inside the createCounter function. The class maintains the state of the counter which includes the current value and the initial value. It provides methods to increment, decrement, and reset the counter.
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.
1class Counter {
2 private int current;
3 private final int initial;
4
5 public Counter(int init) {
6 this.current = init;
7 this.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}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.