Maximum Occurrence Element in an Array

Maximum Occurrence Element In An Array

Find maximum occurrence element in an array in O(n) time and O(1) extra space

Note: Maximum occurrence element which occurred more than half of array.

Algorithm:
  1. Set count = 0
  2. Iterate all array element from start to end
    1. If count == 0 then
      1. Set maxiOccurrenceElement = array[index]
      2. Set increase count (i.e. count++)
    2. Else If maxiOccurrenceElement == array[index] then
      1. Set increase count (i.e. count++)
    3. Else
      1. Set decrease count (i.e. count–)
  3. Validate maxiOccurrenceElement occurred more than half of array.

Latest Source Code:
Github: MaxOccurrenceElement.java


Output:

Array: [1, 2, 1, 3, 1, 5, 1, 6, 1, 2, 2, 1, 4, 1, 1]
Max occurrence element: 1
Author: Hrishikesh Mishra