Explorer
JavaScript

Write a function `createCounter()` that returns an object with `increment()`, `decrement()`, and `getCount()` methods. The count starts at 0.

Problem Statement

<p>Write a function <code>createCounter()</code> that returns an object with <code>increment()</code>, <code>decrement()</code>, and <code>getCount()</code> methods. The count starts at 0.</p>

Examples

Input: const c = createCounter(); c.increment(); c.getCount();

Output: 1

Explanation: Counter internal state incremented from 0 to 1.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Closures allow inner functions to access variables from the outer function. šŸ’” Hint 2: Declare a count variable inside createCounter and return methods that modify it. šŸ’” Hint 3: let count = 0; return { increment: () => ++count, decrement: () => --count, getCount: () => count };

Editorial & Approach

Problem Overview & Intuition

To solve Create a Counter with Closures, we consider the execution characteristics of JavaScript engines. Write a function `createCounter()` that returns an object with `increment()`, `decrement()`, and `getCount()` methods. The count starts at 0. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (closures allow inner functions to access variables from the outer function).
  3. Implement Logic: Handle state and transformations efficiently (declare a count variable inside createcounter and return methods that modify it).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function createCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count,
    getCount: () => count
  };
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Create a Counter with Closures

Easy

Write a function createCounter() that returns an object with increment(), decrement(), and getCount() methods. The count starts at 0.

Example Scenarios
1Example 1
Input: const c = createCounter(); c.increment(); c.getCount();
Output: 1
Explanation:

Counter internal state incremented from 0 to 1.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
2