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#include <functional>
std::function<int(void)> createCounter(int n) {
return [n]() mutable { return n++; };
}C++ leverages lambda expressions with a mutable keyword to allow modification of captured variables. Here, n is passed by value to the lambda, making it mutable so it can be incremented and returned 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 constructor(n) {
3 this.count = n;
4 }
5
6 call() {
7 return this.count++;
8 }
9}JavaScript can use classes to encapsulate the count state. The Counter class's call method returns the current count and updates the internal state.