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

Counter II

Number: 2789

Difficulty: Easy

Paid? No

Companies: Amazon, Google


Problem Description

Design a counter object that supports three operations: increment, decrement, and reset. The counter is initialized with a given starting value, and each method update returns the new counter value.


Key Insights

  • Maintain a current counter value that initially equals the given starting value.
  • The increment function increases the counter by 1.
  • The decrement function decreases the counter by 1.
  • The reset function sets the counter back to its original initialization value.
  • No advanced data structures are needed; a simple variable closure or object state suffices.

Space and Time Complexity

Time Complexity: O(1) for each operation. Space Complexity: O(1) as only a few variables are maintained regardless of input size.


Solution

We can solve this problem by creating a closure (or an object) that encapsulates the current state of the counter along with the initial value. Each provided method (increment, decrement, reset) will access and update this state. The primary trick is to ensure that the reset function always brings back the counter to the original initialization value provided to the createCounter function.


Code Solutions

# Define the createCounter function which takes an initial integer
def createCounter(init):
    # The nonlocal variable current will maintain the current counter value
    current = init
    
    # Define increment: adds 1 to the current counter and returns it
    def increment():
        nonlocal current
        current += 1
        return current
    
    # Define decrement: subtracts 1 from the current counter and returns it
    def decrement():
        nonlocal current
        current -= 1
        return current
    
    # Define reset: resets the current counter to the initial value and returns it
    def reset():
        nonlocal current
        current = init
        return current
    
    # Return an object (dictionary) containing the three functions
    return {
        "increment": increment,
        "decrement": decrement,
        "reset": reset
    }
    
# Example usage:
# counter = createCounter(5)
# print(counter["increment"]())  # Expected output: 6
# print(counter["reset"]())      # Expected output: 5
# print(counter["decrement"]())  # Expected output: 4
← Back to All Questions