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).
Example 1:
Input: n = 10 ["call","call","call"] Output: [10,11,12] Explanation: counter() = 10 // The first time counter() is called, it returns n. counter() = 11 // Returns 1 more than the previous time. counter() = 12 // Returns 1 more than the previous time.
Example 2:
Input: n = -2 ["call","call","call","call","call"] Output: [-2,-1,0,1,2] Explanation: counter() initially returns -2. Then increases after each sebsequent call.
Constraints:
-1000 <= n <= 10000 <= calls.length <= 1000calls[i] === "call"In this approach, we use a closure to maintain the state across multiple calls to the counter function. The closure lets us keep track of the last counted value between function calls.
This Python solution utilizes closures, where the counter function maintains its state using the nonlocal keyword to access and modify the variable n, which isn't local to the function itself. The inner counter function increments this value each time it is called and returns the current count.
JavaScript
C
C++
Java
C#
Time Complexity: O(1) per call.
Space Complexity: O(1) for maintaining the state.
This approach uses object-oriented programming to keep track of the counter's state across multiple invocations by encapsulating the state within a class instance.
This Python solution utilizes a class where the count is maintained as an instance variable. Calling the instance returns the current count, increments it, and stores the new state.
JavaScript
C
C++
Java
C#
Time Complexity: O(1) per call.
Space Complexity: O(1) for the instance state.
| Approach | Complexity |
|---|---|
| Closure-based Approach | Time Complexity: O(1) per call. |
| Class-based Approach | Time Complexity: O(1) per call. |
LeetCode was HARD until I Learned these 15 Patterns • Ashish Pratap Singh • 1,002,262 views views
Watch 9 more video solutions →Practice Counter with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor