Talentd
FleetCode
Make and follow sheets.Sign in

Counter solution and explanation

Easy4 min read81.6% acceptanceUpdated 9 Apr 2026
Counter (Closure - Day2) - Leetcode 2620 - JavaScript 30-Day ChallengeNeetCodeIO · 5:08 · 41K viewsWatch on YouTube
9 more videos on this problem
  1. Counter (Closure - Day2) - Leetcode 2620 - JavaScript 30-Day ChallengeNeetCodeIO · 5:08 · 41K views
  2. Counter | Leetcode 2620 | Closure in Javascript | 30 Days of JavaScript #javascript #leetcodeLearn With Chirag · 6:22 · 5K views
  3. Leetcode javascript day-2 - 2620. Counter, In depth explanation of closures.AnshulOnTech · 5:06 · 3K views
  4. 2620. Counter - Leetcode JavaScript Solution with ExplanationEndeavour Monk · 4:17 · 1K views
  5. #Day2 | 2620. Counter | 30 Days of Javascript | Leetcode-2620| 30 Days Challenge | ClosuresCoding with Ankita · 5:13 · 1K views
  6. 2620. Counter - Day 2/30 Leetcode Javascript ChallengeProgramming Live with Larry · 1:03 · 763 views
  7. 2620. Counter | 30 Days of JavaScript | Closure | JavaScript | EASY EXPLAINATIONcode Explainer · 7:58 · 342 views
  8. Leetcode Day 2 JavaScript Challenge Solution: 2620. CountervanAmsen · 4:27 · 290 views
  9. 2620. Counter Function - Leetcode (Easy). 30 Days of JavaScript | День 2 | Простой счетчикdev tsx · 1:31 · 176 views
  10. LeetCode - 2620. CounterFahim Amin · 7:12 · 172 views

The problem

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).

Example 1:

Input: 
n = 10 
["call","call","call"]
Output: [10,11,12]
Explanation: 
counter() = 10 // The first time counter() is called, it returns n.
counter() = 11 // Returns 1 more than the previous time.
counter() = 12 // Returns 1 more than the previous time.

Example 2:

Input: 
n = -2
["call","call","call","call","call"]
Output: [-2,-1,0,1,2]
Explanation: counter() initially returns -2. Then increases after each sebsequent call.

Constraints:

  • -1000 <= n <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] === "call"

Approach overview

Problem Overview: You start with an integer n. Build a function that returns n on the first call, n + 1 on the second call, and continues increasing by one each time. The key requirement is that the returned function must remember the updated value between calls.

Approach 1: Closure-based Approach (O(1) time, O(1) space)

This approach relies on a closure, where an inner function captures variables from its outer scope. Define a function like createCounter(n) and return another function counter(). The inner function accesses the outer variable n, returns its current value, then increments it. Because the closure keeps a reference to n, the value persists across calls without needing global state. Each call performs a constant-time read and increment operation, so time complexity is O(1), and only one integer is stored, giving O(1) space.

This pattern is common when working with closures and functional programming concepts. It’s concise and maps directly to how languages like JavaScript and Python manage function scope.

Approach 2: Class-based Approach (O(1) time, O(1) space)

A class can also maintain the counter state. Create a class with a field such as count initialized to n. The method that acts as the counter returns the current value and then increments the field. Each invocation simply reads and updates the instance variable. The work per call remains constant, giving O(1) time complexity, and the object stores only one integer, so space complexity is O(1).

This approach mirrors traditional object-oriented design. Instead of capturing variables through a closure, the state is stored explicitly in the object. It can feel more natural in languages where classes are the primary abstraction, such as Java, C++, or C#.

Recommended for interviews: The closure-based solution is usually the expected answer because the problem specifically tests whether you understand how functions can retain state after returning. Showing the class-based version demonstrates that you recognize the underlying concept: persistent state across calls. The closure approach is shorter and idiomatic in languages that support first-class functions, while the class approach highlights the same logic using object-oriented structure.

Approach 1: Closure-based Approach

In this approach, we use a closure to maintain the state across multiple calls to the counter function. The closure lets us keep track of the last counted value between function calls.

def create_counter(n):
    def counter():
        nonlocal n
        current = n
        n += 1
        return current
    return counter
import java.util.function.Supplier;

class Counter {
    public static Supplier<Integer> createCounter(int n) {
        return new Supplier<>() {
            private int count = n;

            @Override
            public Integer get() {
                return count++;
            }
        };
    }
}
#include <functional>

std::function<int(void)> createCounter(int n) {
    return [n]() mutable { return n++; };
}
function createCounter(n) {
    return function() {
        return n++;
    }
}
#include <stdio.h>

typedef struct {
    int (*counter)();
} Counter;

extern Counter createCounter(int n);

static int closureValue;

int counterClosure() {
    return closureValue++;
}

Counter createCounter(int n) {
    closureValue = n;
    Counter c;
    c.counter = counterClosure;
    return c;
}
public class Counter {
    public static System.Func<int> CreateCounter(int n) {
        return () => n++;
    }
}

This Python solution utilizes closures, where the counter function maintains its state using the nonlocal keyword to access and modify the variable n, which isn't local to the function itself. The inner counter function increments this value each time it is called and returns the current count.

Complexity

Time Complexity: O(1) per call.
Space Complexity: O(1) for maintaining the state.

Try this approach in the editor

Approach 2: Class-based Approach

This approach uses object-oriented programming to keep track of the counter's state across multiple invocations by encapsulating the state within a class instance.

class Counter:
    def __init__(self, n):
        self.count = n

    def __call__(self):
        current = self.count
        self.count += 1
        return current
class Counter {
    private int count;

    public Counter(int n) {
        this.count = n;
    }

    public int call() {
        return count++;
    }
}
class Counter {
public:
    Counter(int n) : count(n) {}
    int operator()() { return count++; }
private:
    int count;
};
class Counter {
    constructor(n) {
        this.count = n;
    }

    call() {
        return this.count++;
    }
}
#include <stdio.h>

typedef struct {
    int count;
} Counter;

Counter createCounter(int n) {
    Counter c;
    c.count = n;
    return c;
}

int call(Counter* c) {
    return (c->count)++;
}
public class Counter {
    private int count;

    public Counter(int n) {
        count = n;
    }

    public int Call() {
        return count++;
    }
}

This Python solution utilizes a class where the count is maintained as an instance variable. Calling the instance returns the current count, increments it, and stores the new state.

Complexity

Time Complexity: O(1) per call.
Space Complexity: O(1) for the instance state.

Try this approach in the editor

Approach 3: Default Approach

function createCounter(n: number): () => number {
    let i = n;
    return function () {
        return i++;
    };
}

/**
 * const counter = createCounter(10)
 * counter() // 10
 * counter() // 11
 * counter() // 12
 */
Try this approach in the editor

Complexity comparison

ApproachComplexity
Closure-based Approach

Time Complexity: O(1) per call.
Space Complexity: O(1) for maintaining the state.

Class-based Approach

Time Complexity: O(1) per call.
Space Complexity: O(1) for the instance state.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Closure-based ApproachO(1) per callO(1)Best when the language supports closures and you want concise stateful behavior
Class-based ApproachO(1) per callO(1)Useful in object-oriented languages or when state should be encapsulated in an object

Frequently asked questions

Is Counter easy or hard?

Counter is classified as an Easy problem. The challenge is not algorithmic complexity but understanding how functions or objects can retain state across multiple calls using closures or class fields.

Counter Python/Java solution

In Python, you can implement the counter using a nested function that captures n from the outer scope. In Java or C++, the same behavior can be implemented with a class containing a field that stores the current count and a method that returns and increments it. Both approaches run in O(1) time per call.

How to solve Counter in O(1)?

Store the counter value in a closure or an object field. When the function is called, return the current value and increment it by one. Because the operation only involves reading and updating a single variable, every invocation runs in constant time O(1).

What is the best approach for Counter?

The closure-based approach is typically the best solution. It stores the variable n in the outer function scope and returns an inner function that increments and returns it. Each call runs in O(1) time and uses O(1) space while naturally preserving state between invocations.

Is Counter asked at Google/Amazon/Meta?

Counter represents a common interview concept rather than a company-specific puzzle. It tests understanding of closures, function scope, and persistent state—concepts frequently discussed in JavaScript and Python interviews at companies like Google, Amazon, and Meta.

What data structure is used in Counter?

The solution does not require a complex data structure. It simply stores a single integer as state. That state is maintained either through a closure variable or through an instance variable in a class.

What is the time complexity of Counter?

Each call to the returned counter function performs a constant-time read and increment operation. That means the time complexity per call is O(1). The space usage is also O(1) because only a single integer is maintained as state.

Comments

Now write it yourselfClose this page and solve Counter in the editor, without looking.
Practise Counter