Amazon Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
0
of 0 vote

Sort the array, iterate over it incrementing a counter while you are at the same number. Anytime the counter goes over n/2, print/record/store the element.

You now have what you wanted.

- Anonymous August 14, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#define INVALID_ELEMENT -1

// There can only be one such element not more
int ElementWithMoreThanHalfOccurances(int array[], int length)
{
    int count=0, element,i;
    element = array[0];
    count = 1;
    for(i=1;i<length;i++)
    {
        if(element==array[i])
        {
            count += 1;
        }
        else
        {
            if(count==0)
            {
                element = array[i];
                count = 1;
            }
            else
                count -= 1;
        }
    }
    if(count<= length/2)
        return INVALID_ELEMENT; 
    else
        return element;
}

- Anonymous August 14, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Seems this program will not give correcct results

- selvam August 14, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

are we assuming that all repeated elements are adjacent ?

- gopi.komanduri August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@selvan: What is the input where you see it won't give you correct results?

@gopi: No thats not the assumption.

- fresh_coder August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Why so many crappy people all around? People post code apparently without testing at all. What output this code gives for simplest input like "1 2 1".
here length = 3, and count = 1, i.e. count <= length/2. 1 appears twice here. Why it's too hard for you test your own code?

- hmm August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@hmm.. you can be nice dude!! after all everyone is trying to help each other

anyways the above code is the voting algorithm

cs.utexas.edu/~moore/best-ideas/mjrty/example.html

1. For the above solution to work we should remove the if check "if(count<= length/2) return INVALID_ELEMENT; else" and always return the element.

2. This solution works only if we for sure know if there exists an element with which is repeated n/2 times if not we should go one more pass to verify that...

Read the algo in above link and it will be clear

- vamsu August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

again what happens if input is a[] ={3,4,3,3,4,3,4}.
At the end of iteration count = 1 and element = 4
and if we simply return element then it will be wrong because correct answer is 3.
Please help me out....

- Anonymous November 10, 2011 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

The Above Code is absolutely fine. Those who are having doubt plz visit above link and run this program... foolsssssssss

- ANONYM January 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

sort the array in desc order. Then iterate through the same. keep counting for entire array ... with this appproacl , we can get repeated elementss for n/2 times , then n/4 , n/8 , etc.
complexity .. O(nlogn) // for sorting o(nlogn)+ one scan o(n)

spaace -- o(n) ..

- gopi.komanduri August 15, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You guys make it. Sort first and count.

- xbai@smu.edu August 15, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

There are O(n) time and O(1) space algorithms which don't involve sorting. Search for Finding Repeated Elements paper by Jayadev Misra.

- Anonymous August 15, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Yes, this one does it in one pass and O(1) space. Much better than selection algorithm...

- Anonymous August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

well, if the list has more than n/2 elements repeated, then that, repeated, element would be the median of the list when sorted. So, we can apply selection algorithm to find the median of the list in O(n) time. That means we need to find out the (n/2)th rank element in the list. Similarly, we can find (n/4)th rank element in O(n) time.

Guys, if you have any better solution, please share.

- Jit August 15, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

but that will not confirm that this element was repeated n/2 times in list. it will always result some number as median.

- ankit.atreja August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

If a number repeats more than n/2 times in an array, the median must the number itself. The reverse is surely not true. So, it just gives an indication. You've to scan the array to count how many times the median element occurs indeed.

This method can be extended to 2nd part of the problem by finding n/4th, 2n/4th and 3n/4th element. These are the candidate (there can't have more than 3 elements each repeats > n/4 times). Count the frequency of each of n/4th, 2n/4th, 3n/4th element to validate the indication.

- lol August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Isn't selection O(n^2)? It's impossible to sort within O(n) time, plus you're counting the element, so your solution is already only as good as sort and count.

- Anonymous August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Selection can be done in O(n). Maybe the best selection _you_ can come up with is O(n^2), does not mean others can't do O(n).

Lookup median of medians algorithm on the web.

- Anonymous August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Selection can't be harder than sorting. Then why you believe it'd be O(n^2)? Median of medians algorithm leads to O(n) selection, and O(nlogn) for selection-based sorting (i.e. quicksort).
Using STL nth_element() you can code above in less than 15 lines in O(1) space and expected linear time. Hash is another solution, as pointed by someone else. However, many interviewers not always like hash based solution due to its worst case behavior + space requirements.

- lol August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

another solution can be using a HashTable to keep the number -> count mapping.
complexity:
scanning the array, - O(n)
insert in HashTable - O(1)
get the number with count > n/2 , n/4 - O(1) [hashtable lookup]
Space complexity - O(n) [worst case]

- champion August 15, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I thought of the same thing. Use hash tables and all your problems will be solved. If the element is not present, add it to the hash table and initialize its value to 1. If it is present in the hash table, simply increment its value. Once all the elements are processed, check for elements whose values are >= n/2. The complexity will be O(n) as hashtables have constant time insertion and fetching !

- Rahul December 03, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

i think to find aan element ocuuring more than n/2 times just easy in O(n) algorithm and we can use the moores voting algorithm here
but to extending the problem like n/4 and something like that i think we have to sort first and then we can have the result simply iterating through the list :)

- geeks August 15, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Majority algoritm is the way to go and it already solved above (with minor errors)....

even for n/4 we use the majority algorithm... just reuse the same approach but now ignore the last found majority element (i.e., the one which is more than n/2 times) in the array which running the algo

- vamsu August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Moore's algorithm can't be applied to find n/4. If we apply again to find n/4 element, you will get element that is second most common (could be n/4 but not necessarily)

- Shravan August 16, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Moore's algorithm is "could be algo" .. we need to have one more pass to confirm anything... either it be n/2 or n/4 ..

excerpt from Moore's... ( find which element of a sequence is in the majority, provided there is such an element)

- vamsu August 16, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@vamsu: you are misinterpreting the definition of "majority" here. Majority means more than half (only 1 such element can exist in an array). Applying Moore's algorithm you'd find one element that occurs more than n/4th time. Explained here (2nd post):

ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs;action=display;num=1216999786

But you can't find all 3 of such elements that occur more than n/4th time using this method. Read the 2nd reply to get clarified.

- hmm August 16, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

thanks for the clarification...

I was in a impression that we should to find the n/4 element in the same array which we found n/2 ... if that isn't the case I totally agree

"Design an algorithm to find all elements that appear more than n/2 times in the list. Then do it for elements that appear more than n/4 times."

- vamsu August 16, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

consider array[] = {1 1 1 1 2 3 2}
have an array of size 10,, a[10] = { 0 all elements }
for i from o to sizeof(array): // O(n)
a[array[i]]++ ;
now sort the array based in the value (neglecting value of 0)
should take O(logn) coz numbers r repeated in the sequence n/2 , n/4 , n/8

a[] now has the solution :):)

- viresh a s August 15, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Wrong complexity analysis. Firstly, The input is NOT GUARANTEED to have duplicates. Hence, sorting a[] basically takes O(nlogn) as elements can be all unique in array[]. Secondly, you assume input range is known, which is not given anywhere. Thirdly, what you suggest is basically using hashtable to count frequency. Then, why do you even need sorting? You can just scan through hash table, i.e. a[] taking the top 3.

- lol August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Wait. If an element repeats more than n/2 times, doesn't it have to be the middle element when sorted?

- Jagat August 15, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Go to you desk, and work on paper! Why ask such silly things without trying yourself? In an interview, no one will come to help you to sort out such silly things :P

- hmm August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@hmm... are you nuts ??? answer or don't ... glad I don't work folks like you

- vamsu August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@jagat .. of course

- vamsu August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@vamsu: are you sure JAGAT understood when you write "of course". If he understands just with this, why the hell he couldn't at first! So, isn't it better to construct people in logical ways (the old paper-and-pen style, working with example, drawing tree/graph blah blah) rather spoon-feeding quickly digestible food, which doesn't help to build CONFIDENCE in a person.

- hmm August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

And just to say that JAGAT just spammed the thread asking something that have been clarified by "lol" above. Excerpted from his reply "If a number repeats more than n/2 times in an array, the median must the number itself. The reverse is surely not true. So, it just gives an indication. You've to scan the array to count how many times the median element occurs indeed."

- hmm August 15, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

thats correct jagat...! nice catch... :)
for n/4 you just need to pick 3 numbers.... the n/4th n/2nd and 3n/4th after sorting list.(where n is the length of list)

now we can apply counter on only these three numbers.
It will optimize our algo upto some extent...!!

- PKT August 20, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Ranking is O(n) in worst case too. It doesn't need sorting at all.

- lol August 22, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

@hmm.. agreed to you on "of course"

in general I would like to see people being polite when we are trying help out each other... even your above reply to the comment "Anonymous on August 14, 2011" Fn: ElementWithMoreThanHalfOccurances was arrogant to me

and in fact you mislead that post... check my reply to that comment above ..anyways PEACE :)

- vamsu August 16, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Its a simple Moor's Voting algorithm. For n/4, just do a simple modification to it. This algo finds the element repeated >=n/2 times in a set of elements. Its complete implementation is at wiki, so see it. In case a pseudo code is needed do post for it. Time complexity of this algorithm is O(n).

- Anonymous August 18, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

lol..... why people don't read existing posts before replying? Why they are too restless to write up something crappy!

Applying Moore's algorithm you'd find one element that occurs more than n/4th time. Explained here (2nd post):

ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs;action=display;num=1216999786

But you can't find all 3 of such elements that occur more than n/4th time using this method. Read the 2nd reply to get clarified.

- hmm August 18, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I'm eager to see what is your "do a simple modification"... Post your solution. I'd catch bugs in it!

- hmm August 18, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Moor's Algo does look good for n/2 elements.
But I wonder how this could be applied for n/4,n/8 elements.
Please post a solution for this.m really eager to know about it.

- ayanvit August 19, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void main()
{
int a[10];
int i,check=0,count=1,c;
clrscr();
printf("Enter a");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
c=a[0];
for(i=1;i<10;i++)
{
if(c==a[i])
{
count++;
check=1;
}
else if(c!=a[i] && count>1 && check==1)
{
check=0;
continue;
}
else //if(c!=a[i] &&count>=1 && check==0)
{
count--;
if(count==0)
{
c=a[i];
count=1;
}
}
printf("\n the no is c =%d",c);
}
printf("\n \nthe no is c =%d",c);
}

- Rajeev Kumar August 18, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

WTF! They expect us to solve this in 30 minutes???

- Anonymous August 23, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

WTF! They expect us to solve this in 30 minutes???

- A August 23, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

For n/4.

1) Find the median of the array ( O(n) ) and partition the array around the median
2) Check if median is repeated n/4 times (O (n))
3) Take the left and right parts of the array
4) Check for an element that is repeated more than 50% of elements. If there exists such an element then it is repeated more than n/4 times in the original array


ex: If there are 20 elements, then n/4 = 5.
Partion around the Median --> Partion around position 10
Check if the element at positoin 10 is repeated more than 5 times
Check if there is an element in array from 0..9 that is repeated more than 5 times
Check if there is an element in array from 11..19 that is repeated more than 5 times

- Anonymous August 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

consider an array of 16 elements
for n/2 elemnt will appear more than 8 times
sort the array mid index will contain the requiored elemnt


for n/4 after sorting required number will be at
(0 and 4 both) or
(4 and 8 both) or
(8 and 12) check in interval of 4

- getjar.com/todotasklist my android app August 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

sorry for n/4 sol is wrong
req number can be in between the intervals

- getjar.com/todotasklist my android app August 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This question was asked in google interviews as well.
Here is the solution [For more general algorithm that covers n/m case]

http : / / www[dot]careercup[dot]com / question ? id = 14099679

- Aumit Agrawal September 08, 2013 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More