{"id":410,"date":"2020-03-27T03:37:00","date_gmt":"2020-03-27T03:37:00","guid":{"rendered":"https:\/\/danwritescode.com\/?p=410"},"modified":"2020-06-26T03:50:01","modified_gmt":"2020-06-26T03:50:01","slug":"dominator-codility-100-correct-solution-in-javascript","status":"publish","type":"post","link":"https:\/\/danwritescode.com\/dominator-codility-100-correct-solution-in-javascript\/","title":{"rendered":"Dominator Codility – 100% Correct Solution In Javascript"},"content":{"rendered":"\n
The Dominator Codility Challenge was fun to solve. Its difficulty is marked as easy in Codility and I agree.<\/p>\n\n\n\n
I used an object to hold the number of occurrences of each element and the first index where they appear.<\/p>\n\n\n\n
If one of the occurrences is larger than half of the length of the array then I return the first index of that element.<\/p>\n\n\n\n
function solution(A) {\n if (A.length === 1) return 0;\n let max = 1;\n let maxIndex = -1;\n let occurrence = new Object();\n for (let i = 0; i < A.length; i++) {\n if (occurrence.hasOwnProperty(A[i])) {\n occurrence[A[i]][0]++;\n if (occurrence[A[i]][0] > max) {\n if (occurrence[A[i]][0] > A.length \/ 2) {\n max = occurrence[A[i]][0];\n maxIndex = occurrence[A[i]][1];\n return maxIndex;\n }\n }\n } else {\n occurrence[A[i]] = new Array();\n\n occurrence[A[i]][0] = 1;\n occurrence[A[i]][1] = i;\n }\n }\n\n return maxIndex;\n \n}<\/code><\/pre>\n\n\n\n