Majority Elements in an Array | Moore's Voting Algorithm | Element appears more than Array.length/2


class MostVotedElement {
    
    public static int boyerMooreMaxVoting(int[] array) {
        int maxVotedElement = array[0];
        int count = 1;
        for(int i = 0; i < array.length; i++) {
            count = (maxVotedElement == array[i]) ? ++count : --count;
            // If count is 0 then assign current element as maxVotedElement
            if(count == 0) {
                maxVotedElement = array[i];
                count = 1;
            }
        }
        // Re-validate maxVotedElement
        count = 0;
        for(int element : array) {
            if(maxVotedElement == element) {
                count++;
            }
        }
        return count > array.length/2 ? count : -1; // it will find count if element's
        // frequency is more than array.length/2. 2 Can be any number 3, 4 etc 
    }
        
    public static void main(String args[]){
        int[] array = new int[] {2, 3, 4, 3, 3};
        
        int value = boyerMooreMaxVoting(array);
        
        String result = value == -1 ? "There is no max voted element" : 
            "The max voted element is " + value;
        
        System.out.println(result);
    }
}

Output
The max voted element is 3

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance