Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codility "PermMissingElem" Solution in Javascript

A codility problem asks to find the missing number in zero-indexed array A consisting of N different integers.

E.g.

  Arr[0] = 2
  Arr[1] = 3
  Arr[2] = 1
  Arr[3] = 4
  Arr[4] = 6

I previously submitted a solution that first sorts the array and then performs a forEach function returning the value +1 where the array difference between elements is more than 1, however this doesn't get the 100 points.

Is there a way to improve this?

like image 716
Jose Romero Avatar asked Sep 02 '26 04:09

Jose Romero


2 Answers

Here is 100% javascript solution:

function solution(A) {
    if (!A.length) return 1;
    let n = A.length + 1;
    return (n + (n * n - n) / 2) - A.reduce((a, b) => a + b);
}

We return 1 if the given array is empty, which is the missing element in an empty array.

Next we calculate the 'ordinary' series sum, assuming the first element in the series is always 1. Then we find the difference between the given array and the full series, and return it. This is the missing element.

The mathematical function I used here are series sum, and last element:

  • Sn = (n/2)*(a1 + an)
  • an = a1 + (n - 1)*d
like image 50
RGelman Avatar answered Sep 03 '26 17:09

RGelman


Get 100 in correctness and performance using this function

function solution(A) {
    // write your code in JavaScript (Node.js 4.0.0)
    var size = A.length;
    var sum = (size + 1) * (size + 2) / 2;
    for (i = 0; i < size; i++) {
        sum -= A[i];
    }
    return sum;
}
like image 30
Jose Romero Avatar answered Sep 03 '26 17:09

Jose Romero