#2665

Counter II

Easy
ClosureState Management
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses the same approach as brute force but emphasizes that each function operates in constant time, making it efficient for multiple calls.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable `currentCount` with the value of `init`.
  2. 2Step 2: Define the `increment` function to increase `currentCount` by 1 and return it.
  3. 3Step 3: Define the `decrement` function to decrease `currentCount` by 1 and return it.
  4. 4Step 4: Define the `reset` function to set `currentCount` back to `init` and return it.
  5. 5Step 5: Return an object containing the three functions.
solution.py15 lines
1def createCounter(init):
2    currentCount = init
3    def increment():
4        nonlocal currentCount
5        currentCount += 1
6        return currentCount
7    def decrement():
8        nonlocal currentCount
9        currentCount -= 1
10        return currentCount
11    def reset():
12        nonlocal currentCount
13        currentCount = init
14        return currentCount
15    return {'increment': increment, 'decrement': decrement, 'reset': reset}

Complexity note: The time complexity is O(n) where n is the number of calls made to the functions. Each function operates in constant time, so the overall complexity is linear with respect to the number of operations.

  • 1Functions can maintain state using closures.
  • 2Understanding scope and variable lifetime is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.