Skip to content

Instantly share code, notes, and snippets.

@NeuTrix
Last active December 31, 2021 02:49
Show Gist options
  • Save NeuTrix/cb8d61380a768604c397632dcf28a447 to your computer and use it in GitHub Desktop.
Save NeuTrix/cb8d61380a768604c397632dcf28a447 to your computer and use it in GitHub Desktop.
javaScript solution to Codility PermMissingElem problem (Easy)
// ANSWER:
function solution(A) {
// make a dictionary of expected values: O(n)
let map = []
for (let i = 0; i < A.length + 1; i+= 1) {
map[i] = { num: i+1, bool: -1 }
}
// evaluate subset against dictionary, marking included values: O(n)
for (let j = 0; j < A.length; j+= 1) {
let num = A[j] // find the num in A
map[num -1].bool = 0 // mark as found in map
}
// evaluate dicionary for the missing values: O(n)
for (let k = 0; k < map.length; k+= 1) {
if(map[k].bool === - 1) {
return map[k].num
}
}
}
// QUESTION: https://app.codility.com/demo/results/training64HF3R-BX7/
@yamankatby
Copy link

function solution(A) {
  if (!A.length) return 1;
  A = A.sort((a, b) => a - b);
  for (let i = 0; i < A.length + 1; i++) {
    if (A[i] !== i + 1) {
      return i + 1;
    }
  }
}

@JuanPabloFrersCampos
Copy link

A small improvement to what @yamankatby wrote is to use Unit32Array, in order to sort faster:

function solution(A) { if (!A.length) return 1; A = new Uint32Array(A).sort(); for (let i=0; i<A.length + 1; i++){ if (A[i] !== i+1) return i+1; } }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment