Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

algorithm to find the three majority elements in an array

Tags:

algorithm

Let's say there are three elements in a non-sorted array all of which appear more than one-fourth times of the total number of elements.

What is the most efficient way to find these elements? Both for non-online and online versions of this question.

Thank you!

Edit

The non-online version I was referring to is: this array is specified in full. The online version means the array elements are coming one at a time.

I require the space in addition to time complexity to be tight.

disclaimer: THIS IS NOT HOMEWORK! I consider this as research-level question.

like image 569
Qiang Li Avatar asked Nov 21 '11 01:11

Qiang Li


People also ask

What is the algorithm of array?

Basic OperationsTraverse − print all the array elements one by one. Insertion − Adds an element at the given index. Deletion − Deletes an element at the given index. Search − Searches an element using the given index or by the value.

How do you find the majority element in an array using divide and conquer?

If we know the majority element in the left and right halves of an array, we can determine which is the global majority element in linear time. Here, we apply a classical divide & conquer approach that recurses on the left and right halves of an array until an answer can be trivially achieved for a length-1 array.

What is majority element in an array?

The majority element of an array is the element that occurs repeatedly for more than half of the elements of the input. If we have a sequence of numbers then the majority element appears at least times in the sequence.


2 Answers

Remember up to three elements, together with counters.

  1. remember first element, set count1 = 1
  2. scan until you find first different element, increasing count1 for each occurrence of element 1
  3. remember second elemt, set count2 = 1
  4. scan until you find first element different from elem1 and elem2, incrementing count1 or count2, depending which element you see
  5. remember third element, set count3 = 1
  6. continue scanning, if the element is one of the remembered, increment its count, if it's none of the remembered, decrement all three counts; if a count drops to 0, forget the element, go to step 1, 3, or 5, depending on how many elements you forget
  7. If you have three elements occurring strictly more than one-fourth times the number of elements in the array, you will end up with three remembered elements each with positive count, these are the three majority elements.

Small constant additional space, O(n), no sorting.

like image 122
Daniel Fischer Avatar answered Nov 16 '22 02:11

Daniel Fischer


create a histogram of the entries, sort it, and take the three largest entries.

like image 32
smitec Avatar answered Nov 16 '22 01:11

smitec