Check for Majority Element in a Sorted Array _ GeeksforGeeks

15
5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks 1/15 www.geeksforgeeks.org/archives/4722 GeeksforGeeks A computer science portal for geeks Home Q&A Interview Corner Ask a question Feedback Contribute About us Subscribe Arrays Articles Bit Magic C/C++ Puzzles GFacts Linked Lists MCQ Misc Output Strings Trees Check for Majority Element in a sorted array February 11, 2010 Question: Write a C function to find if a given integer appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 times). In the following programs array is assumed to be sorted in non-decreasing order. METHOD 1 (Using Linear Search) Linearly search for the first occurrence of the element, once you find it (let at index i), check element at index i + n/2. If element is present at i+n/2 then return 1 else return 0.

Transcript of Check for Majority Element in a Sorted Array _ GeeksforGeeks

Page 1: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

1/15www.geeksforgeeks.org/archives/4722

GeeksforGeeks

A computer science portal for geeks

HomeQ&AInterview CornerAsk a question

FeedbackContributeAbout us

SubscribeArraysArticlesBit MagicC/C++ PuzzlesGFactsLinked ListsMCQMiscOutputStringsTrees

Check for Majority Element in a sorted array

February 11, 2010

Question: Write a C function to find if a given integer appears more than n/2 times in asorted array of n integers.

Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size(n) and a number to be searched (x) as parameters and returns true if x is a majority element(present more than n/2 times).

In the following programs array is assumed to be sorted in non-decreasing order.

METHOD 1 (Using Linear Search)Linearly search for the first occurrence of the element, once you find it (let at index i), checkelement at index i + n/2. If element is present at i+n/2 then return 1 else return 0.

Page 2: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

2/15www.geeksforgeeks.org/archives/4722

Time Complexity: O(n)

METHOD 2 (Using Binary Search)Use binary search methodology to find the first occurrence of the given number. The criteriafor binary search is important here.

/* Program to check for majority element in a sorted array */# include <stdio.h># define bool int bool isMajority(int arr[], int n, int x){ int i; /* get last index according to n (even or odd) */ int last_index = n%2? n/2: (n/2 + 1); /* search for first occurrence of x in arr[]*/ for(i = 0; i < last_index; i++) { /* check if x is present and is present more than n/2 times */ if( arr[i] == x && arr[i+n/2] == x) return 1; } return 0;} /* Driver program to check above function */int main(){ int arr[10] = {1, 2, 3, 3, 3, 3, 10}; int n = 7; int x = 3; if(isMajority(arr, n, x)) printf("%d appears more than %d times in arr[]", x, n/2); else printf("%d does not appear more than %d times in arr[]", x, n/2); getchar(); return 0;}

/* Program to check for majority element in a sorted array */

Page 3: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

3/15www.geeksforgeeks.org/archives/4722

# include <stdio.h>;# define bool int /* If x is present in arr[low...high] then returns the index of first occurance of x, otherwise returns -1 */int _binarySearch(int arr[], int low, int high, int x, int n); /* This function returns true if the x is present more than n/2 times in arr[] of size n */bool isMajority(int arr[], int n, int x){ int i = _binarySearch(arr, 0, n-1, x, n); /* check if the element is present more than n/2 times */ if(((i + n/2) <= (n -1)) && arr[i + n/2] == x) return 1; else return 0;} /* Standard Binary Search function*/int _binarySearch(int arr[], int low, int high, int x, int n){ if(high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ /* Check if arr[mid] is the first occurrence of x. arr[mid] is first occurrence if x is one of the following is true: (i) mid == 0 and arr[mid] == x (ii) arr[mid-1] < x and arr[mid] == x */ if(( mid == 0 || x > arr[mid-1]) && (arr[mid] == x)) return mid; else if(x > arr[mid]) return _binarySearch(arr, (mid + 1), high, x, n); else return _binarySearch(arr, low, (mid -1), x, n); } return -1;} /* Driver program to check above functions */int main(){ int arr[10] = {1, 2, 3, 3, 3, 3, 10};

Page 4: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

4/15www.geeksforgeeks.org/archives/4722

Time Complexity: O(Logn)Algorithmic Paradigm: Divide and Conquer

Please write comments if you find any bug in the above program/algorithm or a better way tosolve the same problem.

You may also like following posts

1. Search an element in a sorted and pivoted array2. Majority Element3. Find the smallest and second smallest element in an array4. Median of two sorted arrays5. Given an array A[] and a number x, check for pair in A[] with sum as x

20 comments so far

1. tauseef says:December 18, 2011 at 12:46 AM

If array is sorted its not a problemif(array[mid+1]==array[0] || array[mid-1]==array[last])array[mid] is majority elementelseno majority element exists

int n = 7; int x = 3; if(isMajority(arr, n, x)) printf("%d appears more than %d times in arr[]", x, n/2); else printf("%d does not appear more than %d times in arr[]", x, n/2); getchar(); return 0;}

Send 2people

Page 5: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

5/15www.geeksforgeeks.org/archives/4722

Reply2. baskin says:

March 18, 2011 at 10:35 AM

@GeeksforGeeksHow about this?

ReplySandeep says:March 18, 2011 at 11:00 AM

@baskin:

This approach won't if there is no majority element.

For example, if x is 4, then this will return true for following array

{1, 1, 2, 4, 4, 4, 6, 6}

ReplyAlgoseekar says:April 24, 2011 at 9:02 PM

@sandeep i don't understand ..how make sure about 1st algo..also i think umade code complex..

here is simply implementation

/* Program to check for majority element in a sorted array */# include# define bool int

bool isMajority(int arr[], int n, int x){int i;int count=0;

/* search for first occurrence of x in arr[]*/for(i = 0; i (n/2))return 1;

bool isMajority(int arr[], int n, int x){ return x == arr[n/2];}

Page 6: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

6/15www.geeksforgeeks.org/archives/4722

}return 0;}

/* Driver program to check above function */int main(){int arr[10] = {1, 2, 3, 3, 3, 3, 10};int n = 7;int x = 3;if(isMajority(arr, n, x))printf("%d appears more than %d times in arr[]", x, n/2);elseprintf("%d does not appear more than %d times in arr[]", x, n/2);

getchar();return 0;}

please let know if anything wrong

ReplyAlgoseekar says:April 24, 2011 at 9:05 PM

Also Please Check in Cse of Method You are Passing extra parameter n inbinary search..i don't understand this as wel..see here is i modified program & its working fine

/* Program to check for majority element in a sorted array */#include# define bool int

/* If x is present in arr[low...high] then returns the index offirst occurance of x, otherwise returns -1 */int _binarySearch(int arr[], int low, int high, int x);

/* This function returns true if the x is present more than n/2times in arr[] of size n */bool isMajority(int arr[], int n, int x){int i = _binarySearch(arr, 0, n-1, x);

/* check if the element is present more than n/2 times */if(((i + n/2) = low)

Page 7: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

7/15www.geeksforgeeks.org/archives/4722

{int mid = (low + high)/2; /*low + (high - low)/2;*/

/* Check if arr[mid] is the first occurrence of x.arr[mid] is first occurrence if x is one of the followingis true:(i) mid == 0 and arr[mid] == x(ii) arr[mid-1] arr[mid-1]) && (arr[mid] == x))return mid;else if(x > arr[mid])return _binarySearch(arr, (mid + 1), high, x);elsereturn _binarySearch(arr, low, (mid -1), x);}

/*Return -1 if element does not appear more than n/2 times*/return -1;}

/* Driver program to check above functions */int main(){int arr[] = {1, 3, 3, 3,3,4,10};//sortedint n = 7;int x = 3;if(isMajority(arr, n, x))printf("%d appears more than %d times in arr[]", x, n/2);elseprintf("%d does not appear more than %d times in arr[]", x, n/2);

getchar();return 0;}

Please let me know if anything wrong..???

Reply3. sharat says:

February 24, 2011 at 12:25 AM

Also the Comment/*Return -1 if element does not appear more than n/2 times*/in _binarysearch method seems in appropriate..

Reply

Page 8: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

8/15www.geeksforgeeks.org/archives/4722

4. sharat says:February 24, 2011 at 12:21 AM

in _binarySearch method

There is no use of n, Please remove it.

Reply5. Nitin Taluja says:

January 17, 2011 at 1:11 PM

Soln.1) find the median of the array, as the number repeated more than n/2 times or equal ton/2 times will only be the median

or in other words find the index of(n/2) using modified version of the quicksort.

Reply6. includealldoth says:

December 11, 2010 at 9:27 PM

What if i want to actually find the majority element..divide and conquer would fail.

Reply7. someone says:

December 2, 2010 at 10:02 PM

How about using a hashset?

Reply8. vijayk says:

November 9, 2010 at 8:26 PM

in the linear search method, if condition should be modified as given below or else itwill give wrong result(

similarly in binary search, the if condition should be

Reply9. seeker7 says:

if(a[i] == x && (i+n/2 <= n-1) && a[i+n/2] == x)

if(( mid == 0 || (mid-1 >= 0) && x > a[mid-1]) && (a[mid] == x))

Page 9: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

9/15www.geeksforgeeks.org/archives/4722

October 6, 2010 at 4:13 PM

for linear search array need not b sorted ,so method 1 does not work,in case my inputis:2 3 4 2 2 2 3 2

ReplyGeeksforGeeks says:October 6, 2010 at 4:37 PM

@seeker7: The question is about sorted array only (see title). The method 1 useslinear search to check whether the element is majority or not in a given sortedarray.

Reply10. codegeek says:

September 25, 2010 at 9:29 AM

last comment in _binarySearch() should be/*Return -1 if element is not present in array*/

Replycodegeek says:September 25, 2010 at 10:23 AM

correction:

bool isMajority(int arr[], int n, int x){ /* if mid element is not x then x is not majority element*/ if (n%2 == 0) { if(x != arr[n/2]) return 0; } else if ((x != arr[n/2]) && (x != arr[n/2 - 1])) return 0; int i = _binarySearch(arr, 0, n-1, x, n); /* check if the element is present more than n/2 times */ if(((i + n/2) <= (n -1)) && arr[i + n/2] == x) return 1; else return 0;}

/* if mid element is not x then x is not majority element*/if (n%2 != 0) { if(x != arr[n/2])

Page 10: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

10/15www.geeksforgeeks.org/archives/4722

ReplyShrikant says:December 3, 2010 at 9:33 PM

I agree with this solution.

Reply11. seeker7 says:

August 11, 2010 at 3:30 PM

is there any proof to the logic used i.e. is it is a majority element it should also occur ati+n/2..coz it occurs atleast n/2 times?

Reply12. GeeksforGeeks says:

February 12, 2010 at 8:50 AM

@devendra: x may not be equal to arr[n/2] when it is not a majority element. Forexample arr[] = [1, 2, 3, 4, 4] and x = 4

ReplyAshish says:November 26, 2010 at 12:38 PM

Yaa but integer should occur more than n/2 times ...so it should be minimum n/2+1 times .....so here 4 should be minimum 5/2+1=3 times...

show we will not return 4 as the majority element.

Reply13. devendra says:

February 11, 2010 at 5:34 PM

In above Solution-2 x will always equal to a[n/2] so we dont have to give manually orconsider as a parameter

Reply

Comment

return 0;} else if ((n>=2) && (x != arr[n/2]) && (x != arr[n/2 - 1])) return 0;

Page 11: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

11/15www.geeksforgeeks.org/archives/4722

Name (Required) Email (Required)

Website URI Your Comment (Writing code? please paste your

code between sourcecode tags)

[sourcecode language="C"]/* Paste your code here (You may delete these lines if not writing code) */[/sourcecode]

Have Your Say

Search

Popular Tags

GATEJavaDynamic ProgrammingBacktrackingPattern SearchingDivide & ConquerGraphOperating SystemsRecursion

Page 12: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

12/15www.geeksforgeeks.org/archives/4722

Popular Posts

All permutations of a given stringMemory Layout of C ProgramsUnderstanding “extern” keyword in CMedian of two sorted arraysTree traversal without recursion and without stack!Structure Member Alignment, Padding and Data PackingIntersection point of two Linked ListsLowest Common Ancestor in a BST.Check if a binary tree is BST or notSorted Linked List to Balanced BST

Page 13: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

13/15www.geeksforgeeks.org/archives/4722

250 Subscribe

Forum Latest Discussion

LIS in nlogn timeLast Post By: kartik

Inside: Interview Questions

tree to fileLast Post By: Dheeraj

Inside: Interview Questions

Page 14: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

14/15www.geeksforgeeks.org/archives/4722

Count internal nodes in a binary treeLast Post By: kartik

Inside: Interview Questions

Ancestor of two given leaf nodesLast Post By: dead

Inside: Trees specific questions

combine elements of an array, so as to minimize weights.Last Post By: rohanag

Inside: Interview Questions

FB interview questionLast Post By: ranganath111

Inside: Interview Questions

Testing of factorial of a numberLast Post By: rukawa

Inside: Interview Questions

numeric puzzleLast Post By: asm

Inside: Algorithms

Forum Categories

Interview QuestionsC/C++ Programming QuestionsAlgorithmsTrees specific questionsLinked List specific questionsMultiple Choice QuestionsObject oriented queriesGPuzzles

Page 15: Check for Majority Element in a Sorted Array _ GeeksforGeeks

5/12/12 Check for Majority Element in a sorted array | GeeksforGeeks

15/15www.geeksforgeeks.org/archives/4722

Operating SystemsMiscellaneousJava specific QuestionsPerl specific Questions

Recent Comments

Venki on Structure Member Alignment, Padding and Data Packingavi on Structure Member Alignment, Padding and Data Packingatul on A Program to check if strings are rotations of each other or notVenki on Structure Member Alignment, Padding and Data Packingrahul on Dynamic Programming | Set 13 (Cutting a Rod)Sandeep on Dynamic Programming | Set 3 (Longest Increasing Subsequence)Yueming on Dynamic Programming | Set 3 (Longest Increasing Subsequence)avi on Structure Member Alignment, Padding and Data Packing

@geeksforgeeks, Some rights reservedPowered by WordPress & MooTools, customized by geeksforgeeks team