Skip to main content
Back to problems
Leetcode
Medium
Functions
Design
Counter II

Design a counter object that supports incrementing, decrementing, and resetting its internal value.

Acceptance 0%
Problem Statement

Problem

Implement a function createCounter(n) that returns an object with three methods:

  • increment() increases the current value by 1 and returns the new value.
  • decrement() decreases the current value by 1 and returns the new value.
  • reset() restores the current value back to the original value n and returns it.

The returned object should keep its own independent state for each counter created.

Goal

Use function scope or closures to preserve private state across method calls.

Input Format

  • An integer n used to initialize the counter.
  • Method calls may follow in any order:
    • increment()
    • decrement()
    • reset()

Output Format

  • Each method returns the counter's value after performing its operation.

Constraints

  • The counter must preserve state between method calls.
  • reset() must restore the counter to the initial value passed to createCounter.
  • Multiple counters should not share state.
Examples
Sample cases returned by the problem API.

Example 1

Input

createCounter(5)
call increment()
call increment()
call decrement()
call reset()
call decrement()

Output

6
7
6
5
4

Explanation

Starting from 5: increment -> 6, increment -> 7, decrement -> 6, reset -> 5, decrement -> 4.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.