We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Counter

Number: 2732

Difficulty: Easy

Paid? No

Companies: Google, Meta, Bloomberg, Amazon, Microsoft, Adobe, Apple


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.


Code Solutions

# Python implementation
def counter(n):
    # This is the internal state variable... starting from n.
    current = [n]
    
    def inner():
        # Retrieve the current value
        result = current[0]
        # Increment the number for the next call
        current[0] += 1
        return result
    
    return inner

# Example usage:
# start = counter(10)
# print(start())  # Output: 10
# print(start())  # Output: 11
# print(start())  # Output: 12
← Back to All Questions