NeetCode #945LC-2620EasyJavaScript
← Back to All Problems#945 · #2620 · Counter(计数器)
📌 Problem Statement & Constraints
Given an integer
n, return a counter function. The first call returns n, and every subsequent call returns one more than the previous. Constraints: -1000 <= n <= 1000, at most 1000 calls.💡 Core Algorithmic Approaches
- Use a closure to hold mutable state: the local variable
nis captured by the inner function and survives between calls. - Each call runs
n++(post-increment), which returns the old value and then increments — exactly the required behaviour. - Do not use
++n, which increments first and would make the first call returnn + 1. - This is the classic demonstration of functional state: no class and no global variable is needed.
💻 Benchmark Python3 Implementation
var createCounter = function(n) {
// The closure captures n; n++ returns the old value then increments
return function() {
return n++;
};
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1): every call is constant time.
💾 Space Complexity
O(1): the closure captures a single integer.
⚠️ Interview Pitfalls & Follow-ups
- Using
++n: the first call would returnn + 1instead ofn. - Declaring
nas a global: multiple counters would then interfere with each other. - Recomputing from a separate call count: extra state is unnecessary; a closure increment is simpler.