#2620

Counter

Easy
ClosureState Management
LeetCode ↗

Approaches

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

Intuition

Time O(1) per callSpace O(1)

The optimal solution leverages closures in JavaScript (or similar constructs in other languages) to maintain state without unnecessary overhead. This allows us to efficiently manage the counter with minimal space and time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a function that initializes a counter variable with n.
  2. 2Step 2: Return an inner function that increments and returns the counter variable.
  3. 3Step 3: Each call to the inner function updates the counter in constant time.
solution.py8 lines
1def createCounter(n):
2    count = n
3    def counter():
4        nonlocal count
5        result = count
6        count += 1
7        return result
8    return counter

Complexity note: The time complexity is O(1) for each call because we are simply returning and incrementing a variable. The space complexity is O(1) as we are not using any additional data structures.

  • 1Understanding closures is crucial for maintaining state in functions.
  • 2Incrementing a variable within a closure allows for efficient state management.

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