dominator codility 100% correct javascript solution

Dominator Codility – 100% Correct Solution In Javascript

The Dominator Codility Challenge was fun to solve. Its difficulty is marked as easy in Codility and I agree.

I used an object to hold the number of occurrences of each element and the first index where they appear.

If one of the occurrences is larger than half of the length of the array then I return the first index of that element.

Solution in Javascript with O(N*log(N)) or O(N) complexity

function solution(A) {
  if (A.length === 1) return 0;
  let max = 1;
  let maxIndex = -1;
  let occurrence = new Object();
  for (let i = 0; i < A.length; i++) {
    if (occurrence.hasOwnProperty(A[i])) {
      occurrence[A[i]][0]++;
      if (occurrence[A[i]][0] > max) {
        if (occurrence[A[i]][0] > A.length / 2) {
          max = occurrence[A[i]][0];
          maxIndex = occurrence[A[i]][1];
          return maxIndex;
        }
      }
    } else {
      occurrence[A[i]] = new Array();

      occurrence[A[i]][0] = 1;
      occurrence[A[i]][1] = i;
    }
  }

  return maxIndex;
    
}

Check my solution on Codility.

Leave a Reply