LeetCode Problem Workspace

Counter II

Implement a counter with functions to increment, decrement, and reset it based on an initial value.

category

0

Topics

code_blocks

1

Code langs

hub

0

Related

Practice Focus

Easy · Counter II core interview pattern

bolt

Answer-first summary

Implement a counter with functions to increment, decrement, and reset it based on an initial value.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Counter II core interview pattern

Try AiBox Copilotarrow_forward

The problem involves implementing a counter with three operations: increment, decrement, and reset. The key challenge is ensuring these operations are functional with the provided initial value and sequence of function calls. Proper handling of function calls in the correct order is critical to achieving the expected result.

Problem Statement

You need to implement a function createCounter that accepts an integer init as input. This function should return an object with three methods: increment, decrement, and reset.

The increment method should increase the counter by 1, decrement should decrease it by 1, and reset should return the counter back to its initial value. You should ensure that each operation maintains the expected behavior for any sequence of function calls.

Examples

Example 1

Input: init = 5, calls = ["increment","reset","decrement"]

Output: [6,5,4]

const counter = createCounter(5); counter.increment(); // 6 counter.reset(); // 5 counter.decrement(); // 4

Example 2

Input: init = 0, calls = ["increment","increment","decrement","reset","reset"]

Output: [1,2,1,0,0]

const counter = createCounter(0); counter.increment(); // 1 counter.increment(); // 2 counter.decrement(); // 1 counter.reset(); // 0 counter.reset(); // 0

Constraints

  • -1000 <= init <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] is one of "increment", "decrement" and "reset"

Solution Approach

Object with Methods

You can create an object to hold the counter value and return methods that manipulate it. The increment method will increase the counter by 1, while decrement will decrease it. The reset method will simply return the initial value provided during the creation of the counter.

State Management

The key challenge is maintaining the initial state of the counter. Store the initial value in a variable so that the reset method can revert to it, regardless of how many times other operations have been performed.

Efficiency Considerations

Ensure that each method (increment, decrement, and reset) operates in constant time, O(1), to keep performance optimal even with many function calls.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Both time and space complexity for this problem are O(1) per operation. The time complexity depends on the number of operations performed (constant time per operation). The space complexity is also constant since only a few variables are used to store the state and the methods of the counter.

What Interviewers Usually Probe

  • Focus on correctly implementing the counter functions and their interactions with the initial state.
  • Ensure that each function operates independently and maintains the expected results.
  • Look for clear, concise, and efficient code that directly addresses the problem requirements.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to preserve the initial state of the counter, leading to incorrect results when reset is called.
  • Not handling edge cases, such as calling reset multiple times or performing increment and decrement in rapid succession.
  • Overcomplicating the solution by introducing unnecessary variables or steps.

Follow-up variants

  • Modifying the counter object to support additional operations like multiply or divide.
  • Making the counter operations support negative increments or decrements.
  • Adding support for non-integer initial values (e.g., floating point numbers).

FAQ

What is the core pattern used in the Counter II problem?

The core pattern of this problem revolves around implementing a stateful object with methods to manipulate and reset its state.

How should the reset function behave?

The reset function should return the counter to its initial value, which was provided when creating the counter object.

What happens if the counter functions are called in an unexpected order?

The functions should still work correctly as long as the reset method always returns the initial value, and increment and decrement are applied as expected.

Can the counter support more operations?

Yes, additional operations like multiply or divide can be added, but they should be handled in constant time like the existing methods.

What is the time complexity of this solution?

Each function (increment, decrement, and reset) operates in constant time, O(1), meaning the solution is efficient even for large sequences of function calls.

terminal

Solution

Solution 1

#### TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
type ReturnObj = {
    increment: () => number;
    decrement: () => number;
    reset: () => number;
};

function createCounter(init: number): ReturnObj {
    let val = init;
    return {
        increment() {
            return ++val;
        },
        decrement() {
            return --val;
        },
        reset() {
            return (val = init);
        },
    };
}

/**
 * const counter = createCounter(5)
 * counter.increment(); // 6
 * counter.reset(); // 5
 * counter.decrement(); // 4
 */
Counter II Solution: Counter II core interview pattern | LeetCode #2665 Easy