Intuitive Javascript Solution


  • 5
    D
    var nextGreaterElement = function(findNums, nums) {
        return findNums.map(n => {
            let found = nums.indexOf(n);
            
            if (found !== -1) {
                // find the next greater element's index
                while (nums[++found] < n);
                // -1 if not found
                if (found >= nums.length) found = -1;
                else found = nums[found];
            }
            
            return found;
        });
    };
    

  • 2
    S

    Nice solution :) You don't need the if (found !== -1) check, though, because we know everything in findNums is also in nums.


  • 0
    D

    @sunny-mittal Thanks for the tip!


  • 0
    D

    what a concise solution! thx of sharing


  • 0
    B

    Is there any way somone could explain this:

    while (nums[++found] < n)

    I had always through JS while loops function like this:

    while (condition) {//code block to be executed}

    How is this affecting the latter lines of code? Thanks for the help! Seems like a great solution, just wish I understood it better.


  • 0
    S

    The condition in the while loop executes with each iteration making the block optional. All languages with while loops support it. Just be careful of JS where semicolons are optional due to ASI.


  • 0
    S

    In personally advocate for writing all code without semicolons. They're unnecessarily cluttering and good code shouldn't depend on them.


  • 0
    D

    Hey @BrotherDonkey you're right! But with nothing to execute in the block, the {} is optional.


  • 0
    D

    @sunny-mittal I like how clean codebases are without semicolons. Do you have good practices that can prevent unexpected error for omitting it? I found a good reference but I'm not sure how thorough it is.


  • 0
    B

    Thank you all for your answers!

    In that case, does nums[++found] < n mean that we iterate to the next index of nums (because of ++found), as long as the value is less than n?

    I'd always thought the condition was an expression that evaluated, but didn't really affect the state. I'm kinda a noobie, so forgive me if this doesn't make total sense.


  • 0
    D

    @BrotherDonkey it blew my mind when I found out we can iterate like this! Reading code and asking questions like what you're doing is a great way to learn:) And Yes you're correct. In this case, we update the index and then evaluate the expression.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.