




Sponsored
Sponsored
In this approach, we use a closure to maintain the state across multiple calls to the counter function. The closure lets us keep track of the last counted value between function calls.
Time Complexity: O(1) per call.
Space Complexity: O(1) for maintaining the state.
1def This Python solution utilizes closures, where the counter function maintains its state using the nonlocal keyword to access and modify the variable n, which isn't local to the function itself. The inner counter function increments this value each time it is called and returns the current count.
This approach uses object-oriented programming to keep track of the counter's state across multiple invocations by encapsulating the state within a class instance.
Time Complexity: O(1) per call.
Space Complexity: O(1) for the instance state.
1public class Counter {
2    private int count;
3
4    public Counter(int n) {
5        count = n;
6    }
7
8    public int Call() {
9        return count++;
10    }
11}The state of the counter in C# is stored within an instance variable inside a class. The call method is used to both increment and retrieve the current count value.