Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of size n, with one element n/2 times

Tags:

algorithm

Given an array of n integers, where one element appears more than n/2 times. We need to find that element in linear time and constant extra space.

YAAQ: Yet another arrays question.

like image 491
baskin Avatar asked Apr 13 '09 18:04

baskin


People also ask

How do you check if an element appears twice in an array?

Multiply the array element at that given value (index) with a negative number say -1. If a number have appeared once then the value in the array at that index will be negative else it will be positive if it has appeared twice (-1 * -1 = 1). Find the element with positive value and return their index.

How do you take the size of an array in N?

The size N (or whatever it is named) is the number of items in your array or collection. Since indices are zero-based (as in other languages like C, Python, OCaml, ...), they run from 0 to N – 1. As an example, if you have a 20-item array, N = 20 and the valid indices for this array run from 0 to 19.

How do you find a dominant number in an array?

If there is no such element in the array, return -1. For Example: If the given array ARR = {3,3,3,1,5,6,3} we can see that here 3 occurs 4 times in the array, which is greater than 7/3(N/3), so the dominant number here is 3.


1 Answers

I have a sneaking suspicion it's something along the lines of (in C#)

// We don't need an array
public int FindMostFrequentElement(IEnumerable<int> sequence)
{
    // Initial value is irrelevant if sequence is non-empty,
    // but keeps compiler happy.
    int best = 0; 
    int count = 0;

    foreach (int element in sequence)
    {
        if (count == 0)
        {
            best = element;
            count = 1;
        }
        else
        {
            // Vote current choice up or down
            count += (best == element) ? 1 : -1;
        }
    }
    return best;
}

It sounds unlikely to work, but it does. (Proof as a postscript file, courtesy of Boyer/Moore.)

like image 109
Jon Skeet Avatar answered Nov 16 '22 03:11

Jon Skeet