Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Last active March 7, 2018 08:25
Show Gist options
  • Save Beraliv/8a39c2ffdfca7e53ed431b15999d5600 to your computer and use it in GitHub Desktop.
Save Beraliv/8a39c2ffdfca7e53ed431b15999d5600 to your computer and use it in GitHub Desktop.
Task 76. UniLecs. Check minimal missing value of the permutation. Only natural numbers are considered. The size of the input array is not more than 10000.
const permutation = (arr) => {
let max
const set = []
// set maximum and set
for (let i = 0; i < arr.length; i++) {
const element = arr[i]
// update maximum of elements
if (!max || max < element) {
max = element
}
// set the element is present
if (!set[element]) {
set[element] = true
}
}
// find missing element
for (let i = 1; i < max; i++) {
if (!set[i]) {
return i
}
}
// if not found, return 0
return 0
}
console.log(permutation([ 1, 4, 2, 5, 6 ])) // should be 3
console.log(permutation([ 4, 2, 5, 6 ])) // should be 1, not 3 (1 < 3)
console.log(permutation([ 2, 5, 6 ])) // should be also 1, not 3 or 4 (1 < 3, 4)
console.log(permutation([ 1, 4, 3, 2, 6, 5 ])) // should be 0
console.log(permutation([ 1, 8 ])) // should be 2 (2 < 3, 4, 5, 6, 7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment