2022-03-27

 27 Mar 2022

Find the Lowest Positive Integer that does not exist in Array

Taken from DailyCodingProblem:

Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.

For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.

You can modify the input array in-place.

This is the answer I came up with:

const solution = (array: Array<number>): number | any => {
  // make copy of array, then sort ascending, then filter for positive integers
  let workingArray = array.slice().sort().filter(i => i >= 0)

  // loop through the array and if the incremented value
  // of each element isn't found
  // then increment and return that element
  for (let item of workingArray) {
    if (workingArray.includes(item + 1) == false) {
      let result = item + 1
      return result
    }
  }
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/MYewdgzgLgBBIBsCuUCW4YF4YAoCGATgXgJ4BcMAgkaQDxhIC2ARgKYEB8AlBQy+zAA+MPGBJYOMAN4AoGDAD0CmIzwBrVjFAAHcSABmImiQA0MKAAtWYOCAKw8EYNYAmqMAHMzl6zH2oEKAF9OxhtEAhUNAA3TXcgj3YIORgEVlgAdzs1dw9qYnFsQgKAOggEVGccLjK7KGqS-0D2HFQJGDaObAAGLhkUpVSQEG1zCwIQJA8LMc1i0hEwFw7DHw6wYAJWRmsg5ei8ZFYB5QMYVjxgGdY0nbBYVAgwAHJYEKQlk9mbd03t3cWyy2UCQBBsljwsBu-3uKRCBFwaQeQUYMDOWQIOU8+VIXGkKXkqEMOAxWLyxhKv2QLlYEFaKJgAGoYABGPGYbD6Q4QVh42TyAWpdIwLYQJCBLAdBnMlkEgXA0E2UXiqBygC+KQ1GpkoEgiFYJQQIA8OBS8GQaHAOAA2iyzAAmMzdMwAWgAzGYAKxmAAsZgAHGYAOyu+0AXT6eMGbv6uvNBqNJrNiBQ6DANo9MD9MBddtZEZkUeU9tj4HjhuNpvk5tTVttDqdBaLMBjQA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated October 9, 2024 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems