Problem Description
Implement a counter that is initialized with an integer n. When the counter function is called, it should return n on the first call, then n+1 on the second call, n+2 on the third call, and so on.
Key Insights
- Use a closure or an object/class to retain the state across function calls.
- The solution only requires keeping track of a single integer value that gets incremented.
- Each call to the counter function has constant time and space operations.
Space and Time Complexity
Time Complexity: O(1) per call
Space Complexity: O(1)
Solution
We can solve this problem by capturing the initial value in a closure or by creating an object that maintains the counter state. In the closure approach, the internal state (the current count) is stored in an enclosing scope that persists through multiple calls. In class-based approaches (like in C++ or Java), we maintain a member variable that tracks the state. This solution is straightforward as we simply initialize the counter state with n and then increase it by 1 on each call.