Equi leader javascript 100% correct solution

Equi Leader Codility – 100% Correct Javascript Solution

The Equi Leader Codility challenge builds on top of the previous Dominator challenge.

After we find the leader, we will need to find how many equi leaders there are in the array. An equi leader is an index in the array such as two sequences created by splitting the array at the equi leader index have the same leader as the array.

So, after finding the leader, I iterated through the array and used a stack to keep the indexes of all leaders.

At each step I tested if there are enough leader elements in the left slice and in the right slice so that the current index can be counted as an equi leader.

Solution in Javascript with O(N) complexity

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

            occurance[A[i]][0] = 1
            occurance[A[i]][1] = i
        }
    }

    leader = A[maxIndex]
    
    let equiLeader = 0
    let stack = []
    let stackIndex = -1
    for (let i = 0; i < A.length; i++){

        if (stack.length > (Math.floor(i / 2)  ) && ( maxRepetition - stack.length > Math.floor((A.length - i)/2))){
            equiLeader++
        }
        if (A[i] === leader) stack.push(i)

    }

    
    return equiLeader
    
}

Here is the report and the challenge description as well.

Leave a Reply