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

  1. Keep the current value in a closure variable cur shared by all three methods.
  2. increment uses ++cur (prefix increment: increments then returns); decrement uses --cur; reset assigns cur = init and returns the new value.
  3. Return an object literal whose methods are arrow functions so they share cur correctly (no this is involved here).
  4. 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 increment with cur++: that returns the old value, but the problem wants the value after incrementing.
  • Writing reset as () => { cur = init; }: a block-bodied arrow function does not implicitly return, so it would yield undefined.
  • Storing the value on this.cur: destructuring the methods would detach this; a closure is safer.