Skip to content

Instantly share code, notes, and snippets.

@aginanjar
Created July 6, 2019 04:12
Show Gist options
  • Save aginanjar/297222a320b413ccc5457e1502c8d790 to your computer and use it in GitHub Desktop.
Save aginanjar/297222a320b413ccc5457e1502c8d790 to your computer and use it in GitHub Desktop.
Find the smallest missing integer, unsorted array is given.
let findMissing = (list: Array<number>): number => {
// tentukan nilai terkecil dari bilangan positive int/number
let res = 1
// tentukan nilai terbesar dari array
let max = Math.max.apply(Math, list);
// eliminasi bilangan negative dan 0
let filteredList = list.filter(l => l > 0)
// cari bilangan dengan nilai terkecil (res) hingga terbesar (max) yang tidak termasuk dalam array inputan,
// jika tidak ditemukan , voila~ print!
while(res <= max) {
if (filteredList.indexOf(res) === -1) return res;
res++
}
return res
}
let list1 = [1,2,0]
let list2 = [3,4,-1,1]
let list3 = [7,8,9,11,12]
console.log(findMissing(list1)) // 3
console.log(findMissing(list2)) // 2
console.log(findMissing(list3)) // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment