Codility - PermCheck
by ne on 2022-02-16 under Algo/DS/Problems tagged with codility
/**
* A non-empty array A consisting of N integers is given.
* A permutation is a sequence containing each element from 1 to N once, and only once.
*
* For example, array A such that:
* A[0] = 4
* A[1] = 1
* A[2] = 3
* A[3] = 2
* is a permutation, but array A such that:
*
* A[0] = 4
* A[1] = 1
* A[2] = 3
* is not a permutation, because value 2 is missing.
*
* The goal is to check whether array A is a permutation. Returns 1 if array A is a permutation and 0 if it is not.
*
*/
public class PermCheck {
public int solution(int[] A) {
// write your code in Java SE 8
int[] buck = new int[A.length + 1];
for (int i = 1; i < buck.length; i++) {
buck[i] = 0;
}
for (int i = 0; i < A.length; i++) {
if (A[i] < buck.length)
buck[A[i]]++;
}
for (int i = 1; i < buck.length; i++) {
if (buck[i] != 1) return 0;
}
return 1;
}
}