




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
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.
1#include <stdio.h>
2
3typedef struct {
4    int count;
5} Counter;
6
7Counter createCounter(int n) {
8    Counter c;
9    c.count = n;
10    return c;
11}
12
13int call(Counter* c) {
14    return (c->count)++;
15}In C, a structure is used to encapsulate the state. Each call to the call function requires a pointer to the structure instance to access and modify the current count.