EMChamp Blog

Coding Problems | Calculate if array holds a permutation

This problem can also be called find the missing number in the sequence. What is key to remember is the trick which is for any given sequence 1 to N, its value is given by (N(N+1))/2 . By that you can do all sorts of tricks because you know what the numbers should add up to. In this case if the numbers in the array do not match that formula then you know it is not a permutation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

class Solution {
public int solution(int[] A) {
int N = A.length;
int expectedTotal = N*(N+1)/2;
int actualTotal = 0;
for (int i : A) {
actualTotal+=i;
}

if(actualTotal==expectedTotal)
return 1;
else
return 0;
}
}