DEV Community

Cover image for LeetCode 2620. Counter (Easy)
7

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 ๐Ÿ™๐Ÿฝ.

Developer-first embedded dashboards

Developer-first embedded dashboards

Ship pixel-perfect dashboards that feel native to your app with Embeddable. It's fast, flexible, and built for devs.

Get early access

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 ๐Ÿ’ช

Coherence image

Authenticated AI Chat, Just 15 Lines of Code

Multi-modal streaming chat (including charts) with your existing backend data. Choose from 10+ models from all leading providers. Total control and visibility.

Learn more

๐Ÿ‘‹ Kindness is contagious

Sign in to DEV to enjoy its full potentialโ€”unlock a customized interface with dark mode, personal reading preferences, and more.

Okay