{"id":371,"date":"2020-03-12T01:10:40","date_gmt":"2020-03-12T01:10:40","guid":{"rendered":"https:\/\/danwritescode.com\/?p=371"},"modified":"2020-06-25T04:26:41","modified_gmt":"2020-06-25T04:26:41","slug":"perm-check-codility-100-correct-javascript-solution","status":"publish","type":"post","link":"https:\/\/danwritescode.com\/perm-check-codility-100-correct-javascript-solution\/","title":{"rendered":"Perm Check Codility 100% Correct Javascript Solution"},"content":{"rendered":"\n
The Perm Check Challenge defines a permutation as a sequence containing each element from 1 to N once, and only once. So the order does not matter.<\/p>\n\n\n\n
I devised an algorithm which solves the problem with O(N) or O(N * log(N))<\/strong> complexity.<\/p>\n\n\n\n I look first for the maximum value of the array, N. Then, if the length of the array is different than N, I return 0 – this is not a permutation. <\/p>\n\n\n\n Moving on, then I counted the occurrences of each element in the array in a new array, B. If there is no value 0 in the array, then A was a permutation, otherwise, it was not. <\/p>\n\n\n\n Here is the code:<\/p>\n\n\n\nfunction solution(A) {\n \/\/ write your code in JavaScript (Node.js 8.9.4)\n let max = 0\n for (let i = 0; i < A.length; i++){\n if (A[i] > max) max = A[i]\n }\n\n if (A.length !== max) return 0\n let Indexes = Array(max).fill(0)\n for (let i = 0; i < A.length; i++){\n Indexes[A[i]-1]++\n }\n result = Indexes.indexOf(0)\n if (result === -1) {\n return 1\n } else {\n return 0\n }\n}<\/code><\/pre>\n\n\n\n