Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my for loop breaking earlier than expected?

I am trying to solve a problem on leetCode:

Given an unsorted integer array nums, return the smallest missing positive integer.
This is the code I came up with

var firstMissingPositive = function(nums) {
    nums.sort();
    let x = 1;  //this is to compare the elements of nums
    for (let num in nums) {
      if (nums[num] <= 0) continue; //because anything less than 1 does not matter
      else if (nums[num] != x) break; //if x is not present, x is the answer
      else x++;                      // if x is present, x should increment and check for the next integer
    }
    return x;
};

This code works 106/173 testcases. It does not pass the following case, which looks very simple –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

nums = [1,2,3,4,5,6,7,8,9,20];

The output I get is 3, whereas the expected output is 10.

I’m not looking for the right solution to the problem. I’m just curious why this seemingly simple test fails. I do not understand why my loop breaks at 3 when it passes 1 and 2. Please help!

>Solution :

Here’s the root cause of your problem (mdn):

The sort() method sorts the elements of an array in place and returns
the sorted array. The default sort order is ascending, built upon
converting the elements into strings, then comparing their sequences
of UTF-16 code units values.

So what you get after sort is [1, 2, 20, 3, ...], as ’20’ string precedes ‘3’ string. One possible way to fix this it to force sorting by numeric value:

nums.sort((a, b) => a - b);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading