Difficulty: Easy | Acceptance: 82.40% | Paid: No Topics: N/A
Given an integer n, return a counter function. This counter function initially returns n and then each time it is called, it returns the next integer value.
- Examples
- Constraints
- Approach 1: Closure
- Approach 2: Class-based
- Approach 3: Generator
Examples
Example 1
Input:
n = 10
Output: [10,11,12]
Explanation:
const counter = createCounter(10)
counter() // 10
counter() // 11
counter() // 12
Example 2
Input:
n = -2
Output: [-2,-1,0,1,2]
Explanation:
const counter = createCounter(-2)
counter() // -2
counter() // -1
counter() // 0
counter() // 1
counter() // 2
Constraints
-1000 <= n <= 1000
0 <= calls <= 1000
At most 1000 calls will be made to counter()
Closure
Intuition Use a closure to maintain the counter state in a private variable that persists between function calls.
Steps
- Create an outer function that takes the initial value n
- Declare a local variable to store the current count
- Return an inner function that increments and returns the count
python
def createCounter(n):
count = n
def counter():
nonlocal count
result = count
count += 1
return result
return counterComplexity
- Time: O(1) per call
- Space: O(1)
- Notes: Simple and efficient, uses closure for state management
Class-based
Intuition Use a class to encapsulate the counter state with a method that increments and returns the value.
Steps
- Create a class with a constructor that initializes the counter
- Implement a method that returns the current value and increments it
- Return an instance of the class
python
class Counter:
def __init__(self, n):
self.count = n
def __call__(self):
result = self.count
self.count += 1
return result
def createCounter(n):
return Counter(n)Complexity
- Time: O(1) per call
- Space: O(1)
- Notes: More verbose but provides better encapsulation for complex scenarios
Generator
Intuition Use a generator function to yield incrementing values, maintaining state through the generator’s internal execution context.
Steps
- Create a generator function that yields values starting from n
- Each yield returns the current value and pauses execution
- Resume execution on next call to get the next value
python
def createCounter(n):
def counter_generator():
count = n
while True:
yield count
count += 1
gen = counter_generator()
return lambda: next(gen)Complexity
- Time: O(1) per call
- Space: O(1)
- Notes: Elegant solution using generator pattern, though slightly more overhead