Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

O(n) algorithm to find out the element appearing more than n/2 times

Tags:

c++

I was asked in an interview to give an O(n) algorithm to print an element that appears more than n/2 times in an array, if there is such an element. n is the size of the array. I don't have any clue on how to do this. Can anyone help?

like image 425
softwarematter Avatar asked Dec 21 '10 03:12

softwarematter


People also ask

What is the best time complexity of an algorithm needed to find the largest number in an ordered array?

We have to find the largest/ maximum element in an array. The time complexity to solve this is linear O(N) and space compexity is O(1).

How do you find the top 2 numbers in an array?

Approach: Take two variables; let's call them first and second and mark them as -∞. Iterate through the array and for each element (let's call it current), Compare it with the first and if first is less, assign the first value to second and assign current to first.

How do you find the top 3 of an array?

Solution Approach For the largest three elements, we will create three elements holding their values, max, max2 and max3 and set these values to arr[0]. if (arr[i] > max) -> max3 = max2, max2 = max , max = arr[i]. else if (arr[i] > max2) -> max3 = max2, max2 = arr[i].

How do you find the most occuring element in an array?

A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds the frequency of the picked element and compares it with the maximum so far.


1 Answers

It's the Boyer's Voting algorithm.

It's also O(1) in space!.

Edit

For those complaining about the site color scheme (like me) ... here is the original paper.

like image 53
Dr. belisarius Avatar answered Nov 14 '22 22:11

Dr. belisarius