DEV Community

Cover image for LeetCode 2620. Counter (Easy)

LeetCode 2620. Counter (Easy)

Another day, another LeetCode problem πŸ€“. I hope, you could solve the last problem on your own and fully understand what was happening.

Starting point

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

My Submission

Let's take a look at my code. Yours maybe looks different, and that's okay. Everyone has their own approach.

var createCounter = function(n) {

    return function() {
        let m = n;
        n++
        return m;
    };
};
Enter fullscreen mode Exit fullscreen mode

What happens here?

var createCounter = function(n) {

};
Enter fullscreen mode Exit fullscreen mode

What was given by LeetCode was the outer declaration, the initialization of var createCounter, which was assigned a function that takes one argument, a number n.

πŸ‘» Note: I personally never use var when declaring a variable, I always opt for let or const, but since this was the default, I'll keep it that way (there's nothing really wrong with using var).

Return a function

In the description it is said that we should return a function, which I did by writing

    return function() {

    };
Enter fullscreen mode Exit fullscreen mode

Initial return and increment

The first return should be the number n itself. The next return should be one more then the number before and so on.

let m = n;
n++;
return m;
Enter fullscreen mode Exit fullscreen mode

By declaring m and giving it the value of n, the first time we call the function the value of return m is what is was declared in the beginning, the value of n.

n++, which stand for increment the number n by 1, only happens after m is return. So, the second time we call the function, m will then be m + 1.


In general, I am bad at explaining technical stuff. So any advice is welcome to improve my explanation skills πŸ™πŸ½.

Top comments (2)

Collapse
 
rifat87 profile image
Tahzib Mahmud Rifat

By watching your hard work and dedication to explain the technical stuffs , inspired me to start learn in public.

Collapse
 
yuridevat profile image
Julia πŸ‘©πŸ»β€πŸ’» GDE

Yes, do it @rifat87 πŸ’ͺ