Magicsheet logo

Counter II

Easy
25%
Updated 8/1/2025

Asked by 4 Companies

Topics

Counter II

What is this problem about?

The Counter II interview question is an evolution of the basic counter problem. Instead of just incrementing, you need to return an object with three methods:

  1. increment(): Increases the current value by 1 and returns it.
  2. decrement(): Decreases the current value by 1 and returns it.
  3. reset(): Sets the current value back to the initial starting value and returns it.

Why is this asked in interviews?

Microsoft and Amazon use the Counter II coding problem to test a candidate's ability to create simple APIs using closures or classes. It evaluates how you organize related logic and manage state resets. It’s a classic example of "Encapsulation," where the internal count is hidden from the outside world and only accessible via the provided methods.

Algorithmic pattern used

This problem uses the Object Factory / Closure pattern.

  • An outer function stores the initialValue and a currentValue.
  • It returns an object containing three functions (methods).
  • Each method modifies currentValue and returns the result.

Example explanation

const counter = createCounter(5);

  • counter.increment() -> returns 6.
  • counter.reset() -> returns 5.
  • counter.decrement() -> returns 4. The reset() method specifically needs to remember the original init value passed to the factory function.

Common mistakes candidates make

  • Resetting to 0: Forgetting that reset() must return the original starting value, not necessarily zero.
  • Reference errors: Not correctly referencing the scoped variables inside the returned object.
  • Post-increment confusion: Returning the value before incrementing it, rather than after.

Interview preparation tip

While this can be solved with a Class, using a closure is often preferred in modern JavaScript interviews as it demonstrates a better grasp of the language's functional roots and provides true private variables.

Similar Questions