{"id":367,"date":"2020-03-11T14:29:00","date_gmt":"2020-03-11T14:29:00","guid":{"rendered":"https:\/\/danwritescode.com\/?p=367"},"modified":"2020-06-24T14:39:47","modified_gmt":"2020-06-24T14:39:47","slug":"missing-integer-codility-100-correct-javascript-solution","status":"publish","type":"post","link":"https:\/\/danwritescode.com\/missing-integer-codility-100-correct-javascript-solution\/","title":{"rendered":"Missing Integer – Codility 100% Correct Javascript Solution"},"content":{"rendered":"\n
The Missing Integer problem in the 4th Codility lesson is marked as medium but I think the solution is pretty straight forward.<\/p>\n\n\n\n
The complexity of my solution is O(N)<\/strong> or O(N * log(N))<\/strong>.<\/p>\n\n\n\n First, we check which is the max value of the array. If it is below 0 we immediately return 1.<\/p>\n\n\n\n We then fill an array of length max with the number of occurrences of each positive element from the A array.<\/p>\n\n\n\n Lastly, we check for the first appearance of 0 in the array of occurrence and return the value we were looking for. <\/p>\n\n\n\n.function solution(A) {\n let max = Math.max.apply(null,A);\n if (max < 0) return 1;\n let B = new Array(max).fill(0);\n for (let i = 0; i < A.length; i++) {\n if (A[i] > 0) {\n B[A[i] - 1]++;\n }\n }\n let index = B.indexOf(0);\n if ((index === -1)) {\n return max + 1;\n } else {\n return index + 1;\n }\n}<\/code><\/pre>\n\n\n\n