NeetCode #946LC-2665EasyJavaScript
← Back to All Problems#946 · #2665 · Counter II(计数器 II)
📌 Problem Statement & Constraints
Given an initial value
init, return an object with three methods: increment (adds 1 and returns the current value), decrement (subtracts 1 and returns the current value), and reset (restores init and returns it).💡 Core Algorithmic Approaches
- Keep the current value in a closure variable
curshared by all three methods. incrementuses++cur(prefix increment: increments then returns);decrementuses--cur;resetassignscur = initand returns the new value.- Return an object literal whose methods are arrow functions so they share
curcorrectly (nothisis involved here). - The exercise tests the pattern of multiple methods over shared private state.
💻 Benchmark Python3 Implementation
var createCounter = function(init) {
let cur = init; // private state shared by all methods
return {
increment: () => ++cur, // prefix: increments then returns
decrement: () => --cur,
reset: () => (cur = init), // the assignment evaluates to the new value
};
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1): all three methods are constant time.
💾 Space Complexity
O(1): the closure captures one integer.
⚠️ Interview Pitfalls & Follow-ups
- Writing
incrementwithcur++: that returns the old value, but the problem wants the value after incrementing. - Writing
resetas() => { cur = init; }: a block-bodied arrow function does not implicitly return, so it would yieldundefined. - Storing the value on
this.cur: destructuring the methods would detachthis; a closure is safer.