




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.
1#
In C, closures are not directly supported, so function pointers and global/static variables are used to emulate the behavior. We use a static variable to hold the current count which persists across function calls.
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 {
2public:
3    Counter(int n) : count(n) {}
4    int operator()() { return count++; }
5private:
6    int count;
7};C++ implementation uses a class with an overloaded operator() to mimic function calls. The count is incremented and returned by invoking the instance like a function.