LeetCode Problem Workspace
Counter
Implement a counter function that returns increasing integers starting from a given initial value with each call, leveraging closures.
0
Topics
1
Code langs
0
Related
Practice Focus
Easy · Counter core interview pattern
Answer-first summary
Implement a counter function that returns increasing integers starting from a given initial value with each call, leveraging closures.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Counter core interview pattern
This problem asks for a counter function that starts at a specified integer n and returns n, then n+1, n+2, etc., on each call. The solution relies on closures in JavaScript to preserve state across multiple invocations. Using a simple inner function that updates a variable on each call ensures correct sequential output without external state management.
Problem Statement
Given an integer n, implement a counter function that initially returns n and increments by 1 each time it is called. You must return a function that can be called multiple times, producing the sequence n, n+1, n+2, and so on.
For example, calling the counter with n=10 and invoking the function three times should return 10, 11, and 12. Constraints include -1000 <= n <= 1000 and up to 1000 calls, where each call is represented by the string 'call'.
Examples
Example 1
Input: n = 10 ["call","call","call"]
Output: [10,11,12]
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]
counter() initially returns -2. Then increases after each sebsequent call.
Constraints
- -1000 <= n <= 1000
- 0 <= calls.length <= 1000
- calls[i] === "call"
Solution Approach
Use a Closure to Maintain State
Define an outer function that takes n and returns an inner function. The inner function references a variable declared in the outer scope and increments it each time it is called, preserving state across calls.
Increment on Each Call
Inside the returned function, increment the counter variable before returning its value. This ensures each invocation returns one more than the previous call, satisfying the pattern of sequential increments.
Handle Edge Cases and Constraints
Ensure that the initial n can be negative or zero and that the function can handle up to 1000 calls without error. No special handling for large numbers is needed within given constraints.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity is O(1) per call since each function invocation simply increments a variable. Space complexity is O(1) for storing the counter state within the closure.
What Interviewers Usually Probe
- Checking for correct closure usage to maintain state
- Ensuring sequential increment without external variables
- Understanding how to return a function that preserves local state
Common Pitfalls or Variants
Common pitfalls
- Forgetting to use closure and losing the counter state
- Incrementing after returning instead of before leading to off-by-one errors
- Assuming counter must reset or using global variables incorrectly
Follow-up variants
- Implement a counter that decrements instead of increments
- Allow the counter to increment by a step value other than 1
- Create multiple independent counters starting from different n values
FAQ
What is the main pattern in the Counter problem?
The core pattern is maintaining internal state across multiple calls using a closure so each call returns the next integer.
Can the Counter function start with a negative number?
Yes, the counter can start at any integer between -1000 and 1000 according to the problem constraints.
How does the closure preserve the counter value?
The returned inner function retains access to the outer function's variable, which holds the current counter value, incrementing it on each call.
What is the expected output for multiple calls?
Each call to the counter function should return the previous value plus one, producing a sequential integer sequence.
Is this pattern only used in JavaScript?
No, closures exist in many languages, but this problem specifically leverages JavaScript closures to track counter state.
Solution
Solution 1
#### TypeScript
function createCounter(n: number): () => number {
let i = n;
return function () {
return i++;
};
}
/**
* const counter = createCounter(10)
* counter() // 10
* counter() // 11
* counter() // 12
*/