Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to get the first missing smallest positive integer in an unsorted integer array with JavaScript

2 Answers

0 votes
function firstMissingPositive(arr) {
  const size = arr.length;

  // Step 1: Place each number in its correct position if possible
  let i = 0;
  while (i < size) {
    const correctPos = arr[i] - 1;
    if (arr[i] > 0 && arr[i] <= size && arr[i] !== arr[correctPos]) {
      // Swap arr[i] with arr[correctPos]
      [arr[i], arr[correctPos]] = [arr[correctPos], arr[i]];
    } else {
      i++;
    }
  }

  // Step 2: Find the first missing positive integer
  for (i = 0; i < size; i++) {
    if (arr[i] !== i + 1) {
      return i + 1;
    }
  }

  // If all numbers are in place, the missing integer is n + 1
  return n + 1;
}

const arr = [3, 4, -1, 1];
const missing = firstMissingPositive(arr);
console.log('The first missing smallest positive integer is:', missing);



/*
run:

The first missing smallest positive integer is: 2

*/

 



answered Jun 4, 2025 by avibootz
0 votes
function findSmallestMissingNumber(arr) {
    let numSet = new Set(arr);
    
    let index = 1;
    while (true) {
        if (!numSet.has(index)) {
            return index;
        }
        index++;
    }
}

const arr = [3, 4, -1, 1];
console.log(findSmallestMissingNumber(arr));



/*
run:

2

*/

 



answered Jun 4, 2025 by avibootz
...