Skip to main content
Back to problems
#2620
Easy JavaScript

Counter

82.4% acceptance
Mar 2, 2026
1617
129
Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).

Solution

TypeScript
Time O(1)
Space O(1)
LeetCode
solution.ts
function createCounter(n: number): () => number {
  let count = n;
  return function () {
  return count++;
  };
}

/**
 * const counter = createCounter(10)
 * counter() // 10
 * counter() // 11
 * counter() // 12
 */