




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.
1import 
Java utilizes anonymous inner classes and functional interfaces to simulate closures. The Supplier interface is used here to maintain and update the state, keeping track of the counter through repeated calls to its get method.
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    private int count;
3
4    public Counter(int n) {
5        this.count = n;
6    }
7
8    public int call() {
9        return count++;
10    }
11}A Java class maintains the counter state with an instance variable. The call method provides the required functionality of returning and incrementing the private state.