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

Counter

Difficulty: Easy


Problem Description

Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).


Key Insights

  • The counter function needs to maintain internal state to keep track of how many times it has been called.
  • The initial value returned should be n, and each subsequent call should increment this value by 1.
  • The solution requires a closure to encapsulate the state of the counter between calls.

Space and Time Complexity

Time Complexity: O(1) per call (constant time for each function invocation) Space Complexity: O(1) (constant space for the counter's internal state)


Solution

To solve this problem, we can use a closure that captures the value of n and maintains a counter variable. The closure will return a function that increments and returns the value each time it is called. The data structure used is a simple integer to track the current count, and the algorithm is straightforward with constant time complexity since each call simply increments a number.


Code Solutions

def create_counter(n):
    count = n  # Initialize the counter with n
    def counter():
        nonlocal count  # Access the non-local variable count
        result = count  # Store the current count to return
        count += 1  # Increment the count for the next call
        return result  # Return the current count
    return counter  # Return the inner counter function
← Back to All Questions