Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!