Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NeuTrix/ef1558493a6c2fdbc0ebb57c8a55be31 to your computer and use it in GitHub Desktop.
Save NeuTrix/ef1558493a6c2fdbc0ebb57c8a55be31 to your computer and use it in GitHub Desktop.
A simple javascript solve to the Codility PermCheck challenge
// ===== ANSWER:
function solution(A) {
let set = new Set(); // holds a unique set of values
let max = 1; // largest number in set
let min = 1; // smallest number in set
let n = A.length
for (let i = 0; i < n; i += 1) {
let num = A[i];
if (num > max) {
max = num; // determine max
} else if (num < min) {
min = num; // determine min
}
set.add(num) // only permits unique values
}
let m = set.size // size of set
let range = (max - min) + 1 // size of a sequential permutaion, give range
// conditions required to solve puzzle
return n === m && range === m ? 1 : 0
}
// ===== QUESTION:
// https://app.codility.com/demo/results/training3X96VM-H3Z/
/*
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.
Write a function:
function solution(A);
that, given an array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
the function should return 1.
Given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
the function should return 0.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [1..1,000,000,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
*/
@Kekelii
Copy link

Kekelii commented Aug 22, 2022

My solution scored a 100%

function solution (arr){
    let ln = arr.length;
    let set = new Set(arr);
    let max = Math.max(...arr)
    if(ln==max && ln == set.size){ 
            //length of the array has to be equal to the size of the set and max value of the array
        return 1
    }
 return 0
}

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