Microsoft Interview Question for Interns


Country: India
Interview Type: In-Person




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

Moore's Voting Algorithm

- Bruce October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Moore's voting algorithm gives the right answer
only if it has the majority element.
Otherwise, it gives a wrong answer,
and there is no indication it is not the actual majority.

For example,
AAABBBC, will give the current status (C,1) at the end.

Hence, given an answer, we have to check
whether it is the actual majority.

- lenvanthis October 25, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

With corrections as mentioned by other genius...
First iteration gives you a probable candidate with highest votes but that candidate may not be in majority per definition of the question.
So you have to run additional loop to make sure that candidate has >N/2 votes.

- Sandy November 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
5
of 5 vote

Step 1: Moore's voting algorithm -> this will give one element as Majority element.

Step 2: Make one more pass on array. Count the element obtained above. If count >= len/2 then there is a majority element and that is the one obtained in step 1.
if count <len/2 that means array has no majority element.

- Ragha October 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Stack is good a idea!!

- Anonymous November 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

Just start pushing all the elements into hash map and increment the count on insertion. Store maximum count in a local variable.

Check this count at length /2 + 1 if its not greater than 1 - quit
similarly check it at length / 2 + 1 if its not greater than 2 - quit

Perhaps this would be the most optimum with complexity O(n).

- Anonymous October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

But the space complexity is O(N).
A better method is to use Moore's voting Agorithms (DarkKnight's response above) and then verifying if the results obtained are indeed the majority element. Both can be done in O(N) time.

- artemis October 30, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 3 vote

Assumption : there EXISTS a majority element
Logic : keep a record of majority element candidate and its count so far, if the next number matches, increase the count, else decrease the count, if count = 0, set candidate = current number
Time Complexity : O(n)

int candidate = 0;
int count = 0;
for i = 0 to n - 1
    if(count==0)
        candidate=a[i];
    else if(a[i]==candidate)
        count++;
    else
        count--;
end for
print candidate

- DarkKnight October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is wrong. Here you are making assumption that the first element in the array itself is the majority element and that's wrong. Majority element could start from any index in the array till length/2.

- Mario October 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

i don't think your algorithm will work on input { 2,1,2}. (the input array isn't sorted}

- feras October 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Actually whatever element the candidate holds at the end (irrespective of its count at the end), will be the majority element(if there exists one)
For eg: {2, 1, 2}
when i = 0, arr[i] = 2, Start with candidate = 2, count = 1;
when i = 1, arr[i] = 1, candidate = 1, count = (1-1)+1 = 0. Since arr[i] != candidate we decrement count, then change candidate element whenever count reaches 0, and then increment count for this new value of candidate.
when i = 2, arr[i] = 2, candidate = 2, count = 1-1+1 = q (similarly)

So at the end candidate = 2 (There will always be a candidate element at the end of the algo)

So, now 2 is the majority element if there exists one in the array. To be sure, just runa scan once again and maintain a counter only for 2. If it is > n/2 then 2 is the answer

- artemis October 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

nice solution but needs a bit of correction...
initialization is not done properly...

candidate=a[0];
count=1;

this should be the initialization...then the algorithm will yeild proper results

- sourav.hitk November 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Posting in the correct thread.
With corrections as mentioned by other genius...
First iteration gives you a probable candidate with highest votes but that candidate may not be in majority per definition of the question.
So you have to run additional loop to make sure that candidate has >N/2 votes.

- Sandy November 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

this algorithm fails with this test case

{2,4,2,5,2,2,6,6,6};

- kern November 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ kern in u'r test case, 2 came for 4 times in 9 elements. As per question, major element comes more than n/2 (min n/2 +1) times.

- bharat November 14, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

To add to the above code one more terminating condition would be when count reaches length / 2

- Anonymous October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use a stack buddy, use a stack :D

- Phuoc November 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

candidate = a[0];
count =1;
for(int i=1;i<n;i++)
{
if(candidate == a[i])
count++;
else
{
count--;
if(count == 0)
{
count =1;
candidate = a[i];
}
}
}
if(count > 1)
major element present and "candidate" is major element.

- bharat November 14, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

If i am getting the question correctly then i think this approach can work-
sort the array and check if
a[n/2-1]==a[n/2] and a[n/2+1]==a[n/2] if n is even
or
a[n/2-1]==a[n/2] or a[n/2+1]==a[n/2] if n is odd

then its majority element else majority element doesn't exist.

its O(nlogn)

- taani November 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1.Create linklist having data part,count and link part;
data will store the value.
Count will store the no of duplicate of data.
next will link to next node.
e.g.
struct linklist{
int data;
int count;
struct node *next;
}
2.travers the linklist to find node having the maximun value of count;

- sonu December 15, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Each time when we will add the node we will traverse the LL and
1. if any duplicate element is found we will simply increment the count value.
2.Otherwise we will add the node.

- sonu December 15, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class MajorityElement {
	
	//Moore's Voting Algorithm
	public static Integer majorityEle(int[] array) {
		if (array == null && array.length == 0) {
			return null;
		}
		int candidate = 0;
		int count = 1;
		for (int i = 1; i < array.length; i++) {
			if (array[i] == array[i - 1]) {
				count++;
			} else {
				count--;
			}
			if (count == 0) {
				candidate = i;
			}
		}
		count = 0;
		for (int i = 0; i < array.length; i++) {
			if (array[i] == array[candidate]) {
				count++;
			}
		}
		if (count > array.length / 2) {
			return array[candidate];
		}
		return null;
	}

	public static void main(String[] args) {
//		int[] array = {3,3,4,4,5,3,3,4};
		int[] array = {2,4,2,5,2,2,6,6,6};
		System.out.println(majorityEle(array));
	}

}

- Kevin March 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

jj

- hhh March 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean CompareWithOtherElements(int [] S, int data, int start, int end ){
for(int i = start; i<= end; i++){
if(S[i] == data){

return true;
}
}

return false;
}

public static int FindMajorEl(int [] S , int start, int end){
boolean Found = false;

if(end - start == 0){return S[start];}
if(end - start == 1){
if(S[start] == S[start + 1]){
return S[start];}
}
int mid = ((end - start + 1) / 2);
int ret = FindMajorEl(S, start, start + mid - 1);
if(ret != -1){
Found = CompareWithOtherElements(S,ret,start+ mid, end );
}
if(Found == false){
ret = FindMajorEl(S, start + mid, end);
if(ret != -1){
Found = CompareWithOtherElements(S,ret,start,start + mid -1);
}
}
if(Found){ return ret;}
else {return -1;}
}

- Shriganth March 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Step 1 ) Just sort the array
Step 2 ) Compare the middle element with the first element , If equal majority number exists and return Mid.
If not equal then majority element does not exist -> Time Complexity - O(nlogn)

- Rushil October 14, 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