Counter Problem
#2620
Description
LeetCode Problem 2620.
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"
Solution
Approach: Closure over the next value
createCounter has to remember a number between calls, and each counter must have its own number. A closure does exactly that.
- The outer function keeps a local variable
next, initiallyn. - The returned function gives back
nextand then increases it;next++returns the old value first, so the first call yieldsn.
Because next is created inside createCounter, two counters never interfere with each other, which a module-level variable would not guarantee.
Complexity: time O(1) per call, space O(1).
/**
* @param {number} n
* @return {Function} counter
*/
var createCounter = function (n) {
let next = n;
return function () {
return next++;
};
};
/**
* const counter = createCounter(10)
* counter() // 10
* counter() // 11
* counter() // 12
*/