pyNoob
pyNoob

Reputation: 37

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 -

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!

Upvotes: 0

Views: 184

Answers (1)

raina77ow
raina77ow

Reputation: 106385

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

Upvotes: 1

Related Questions