




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.
1function createCounterJavaScript makes use of closures to maintain the state. The counter function is generated by createCounter, and it retains access to the variable n from its creation environment, allowing it to increment and return the value of n on each call.
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.
1class Counter:
2    def __init__(self, n):
3        self.count = n
4
5    def __call__(self):
6        current = self.count
7        self.count += 1
8        return currentThis Python solution utilizes a class where the count is maintained as an instance variable. Calling the instance returns the current count, increments it, and stores the new state.