Missing element in Permutation.

Jul 21, 20202 mins read

An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

Your goal is to find that missing element.

Write a function:

1
2function solution(A) {
3}
4

that, given an array A, returns the value of the missing element.

For example, given array A such that:

  • A[0] = 2
  • A[1] = 3
  • A[2] = 1
  • A[3] = 5

the function should return 4, as it is the missing element.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [0..100,000];
  • the elements of A are all distinct;
  • each element of array A is an integer within the range [1..(N + 1)].

Points to be Taken

1.1

1
2function solution(A) {
3 const b = A.sort()
4 for(let i=0;i<=b.length;i++) {
5 if(b[i+1] !== b[i] + 1) {
6 return b[i] + 1
7 }
8 }
9 return ''
10}
11

1.2

1
2function solution(A) {
3 const n = A.length + 1
4 const sumOfN = Math.floor(n * (n + 1) / 2)
5 const sumOfAll = A.reduce((a, b) => a + b, 0)
6 return sumOfN - sumOfAll
7}
8

Points to be Taken

  1. Array problem expect empty array condition check and single element check.
  2. Arithmetic progression