Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

15
5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks 1/15 www.geeksforgeeks.org/archives/12164 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 Count the number of occurrences in a sorted array May 3, 2011 Given a sorted array arr[] and a number x, write a function that counts the occurrences of x in arr[]. Expected time complexity is O(Logn) Examples: Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 2 Output: 4 // x (or 2) occurs 4 times in arr[] Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 3 Output: 1 Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 1 Output: 2

Transcript of Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

Page 1: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

GeeksforGeeks

A computer science portal for geeks

HomeQ&AInterview CornerAsk a question

FeedbackContributeAbout us

SubscribeArraysArticlesBit MagicC/C++ PuzzlesGFactsLinked ListsMCQMiscOutputStringsTrees

Count the number of occurrences in a sorted array

May 3, 2011

Given a sorted array arr[] and a number x, write a function that counts the occurrences of x inarr[]. Expected time complexity is O(Logn)

Examples:

Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 2 Output: 4 // x (or 2) occurs 4 times in arr[]

Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 3 Output: 1

Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 1 Output: 2

Page 2: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 4 Output: -1 // 4 doesn't occur in arr[]

Method 1 (Linear Search)Linearly search for x, count the occurrences of x and return the count.

Time Complexity: O(n)

Method 2 (Use Binary Search)1) Use Binary search to get index of the first occurrence of x in arr[]. Let the index of the firstoccurrence be i.2) Use Binary search to get index of the last occurrence of x in arr[]. Let the index of the lastoccurrence be j.3) Return (j – i + 1);

/* if x is present in arr[] then returns the count of occurrences of x, otherwise returns -1. */int count(int arr[], int x, int n){ int i; // index of first occurrence of x in arr[0..n-1] int j; // index of last occurrence of x in arr[0..n-1] /* get the index of first occurrence of x */ i = first(arr, 0, n-1, x, n); /* If x doesn't exist in arr[] then return -1 */ if(i == -1) return i; /* Else get the index of last occurrence of x. Note that we are only looking in the subarray after first occurrence */ j = last(arr, i, n-1, x, n); /* return count */ return j-i+1;} /* if x is present in arr[] then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */int first(int arr[], int low, int high, int x, int n){ if(high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ if( ( mid == 0 || x > arr[mid-1]) && arr[mid] == x) return mid;

Page 3: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

Time Complexity: O(Logn)Programming Paradigm: Divide & Conquer

Please write comments if you find the above codes/algorithms incorrect, or find other ways tosolve the same problem.

You may also like following posts

else if(x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid -1), x, n); } return -1;} /* if x is present in arr[] then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */int last(int arr[], int low, int high, int x, int n){ if(high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ if( ( mid == n-1 || x < arr[mid+1]) && arr[mid] == x ) return mid; else if(x < arr[mid]) return last(arr, low, (mid -1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1;} /* driver program to test above functions */int main(){ int arr[] = {1, 2, 2, 3, 3, 3, 3}; int x = 3; // Element to be counted in arr[] int n = sizeof(arr)/sizeof(arr[0]); int c = count(arr, x, n); printf(" %d occurs %d times ", x, c); getchar(); return 0;}

Send Be thefirst of

Page 4: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

1. Check for Majority Element in a sorted array2. Floor and Ceiling in a sorted array3. Program to count number of set bits in an (big) array4. Search an element in a sorted and pivoted array5. Count Inversions in an array

20 comments so far

1. Anuj Bansal says:November 13, 2011 at 6:53 PM

Here is a code that also works in O(lgN).

#include<stdio.h>#include<math.h>#define MAX 12 int number(int a[MAX], int low, int high, int x) { if(low <= high) { int mid,i,j; mid = (low+high)/2; if(a[mid] == x) { i = number(a,low,mid-1,x); j = number(a,mid+1,high,x); if(i != -1 && j != -1) return i+j+1; else if(i == -1 && j != -1) return j+1; else if(j== -1 && i != -1) return i+1; else return 1; } else if(a[mid] > x) return number(a,low,mid-1,x); else return number(a,mid+1,high,x); } else return -1;}

Page 5: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

Reply2. Ankur says:

October 4, 2011 at 2:46 AM

If mid==0 or mid==n-1 then the function returns mid

Now if the element is not present then the result will be wrong

Here i think we should put a check before return mid statement thatif(mid==0){if(x!=a[mid]) return -1}similarly for Last func

Reply3. LoneShadow says:

August 18, 2011 at 6:53 AM

The function first doesnt seem to work for the following input. For example, array is0,1,1,2,3, and I am looking for the first occurrence of 1.

Start with low=0, high= 4, x=1.1. Mid = 2, and since arr[mid-1] is not less than x(arr[mid-1] is arr[1], which is 1), itwill end up calling the function again with parameters 0, 1

2. With 0,1 as low and high mid will be (0+1)/2, which is 0. The first conditional wilfail,( mid == 0, but the && part is not true, a[mid] is a[0], which is NOT equal to 1).So the function will be called again with low, mid-1, which is 0,0.

3. This will eventually return -1, which is wrong.

Also, not really sure why n is being passed into first/last. Not being used as far as I cansee.

ReplyLoneShadow says:August 18, 2011 at 6:57 AM

One fix I can think off the top of my head is to call the function again with low,mid instead of low, mid-1, since you want to include the value of mid itself (its

int main() { int a[MAX]={1,1,3,3,3,3,7,7,7,11,11,12}; printf("%d\n",number(a,0,MAX-1,7)); return 0;}

Page 6: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

equal, not less or more to be excluded).

ReplyLoneShadow says:August 18, 2011 at 7:10 AM

Sorry, my bad. Worked it out.

Reply4. skulldude says:

July 16, 2011 at 3:54 PM

Well, can someone tell me why in the second method is the condition (m==0) includedwhile checking if the middle element is the required element?

Replyhari6988 says:August 11, 2011 at 11:22 PM

if mid was 0 , arr[mid-1] will reference arr[-1] and it will cause the error .samecase with mid==n-1||x<arr[mid+1]

Reply5. Jatin Sanghvi says:

July 12, 2011 at 1:52 AM

shouldn't work. take arr = [1,3] and search for 2.

ReplyGeeksforGeeks says:July 12, 2011 at 9:55 AM

@Jatin Sanghvi: The given code works fine for your example. It returns -1 whenthe given number is not present.

Reply6. foobar says:

June 19, 2011 at 10:13 PM

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

public static void CountNumberOfOccurences(){ /* * Count the number of occurrences in a sorted array

Page 7: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

Reply7. saji says:

May 12, 2011 at 1:48 PM

while invoking the method last , will using the args

last(arr, i, n-1, x, n) instead of last(arr, 0, n-1, x, n) cause any issues?

ReplyGeeksforGeeks says:May 12, 2011 at 2:44 PM

@saji: Thanks for suggesting the optimization. It doesn't cause any problem. Wehave updated the code with the suggested changes.

* Given a sorted array arr[] and a number x, write a function that counts the occurrences of x in arr[]. Expected time complexity is O(Logn) * */ int[] arr = {1, 1, 2, 2, 2, 2, 3,}; int n = 2; int res = Array.BinarySearch(arr, 2); int found = res; int count = 0; if(res > 0) { count++; } while(arr[--res] == 2) { count++; } res = found; while(arr[++res] ==2) { count++; } Console.WriteLine(res); }

Page 8: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

Reply8. nandini says:

May 5, 2011 at 2:43 AM

Isn't the complexity of the algorithm in Method2 O(n) in the worst case?

eg: {2,2,2,2,2}program will start from mid-index and then will shift one-by-one towards left to find'first' and then one-by-one right to find 'last' in each loop.

ReplySandeep says:May 5, 2011 at 7:52 AM

@nandini: Please take a closer look at the program, it recursively divide the arrayinto two halves. Time complexity is: T(n) = T(n/2) + C which is O(Logn)

Replythechamp says:May 10, 2011 at 9:59 PM

you have chosen an example where number of elements are so less that it appearsa sequential search but it is a binary search only

Reply9. WgpShashank says:

May 3, 2011 at 6:11 PM

Hi Sandeep It Can be done more simply using

Modified Binary Search Algorithm

calculate mid=low+high/2;if(a[mid]>num)search in right side & set low=mid+1 & return ;else if(a[mid]search in left side of mid set high=mid-1 & return ;else //its important instead of just of printing the num or incrementing the counter //itried if you will do like this then it will be O(n) not O(logn) , si i will add 1 to recursivelycall for left side + recursively call for right side so every time this line executes we areincrementing the counter &return 1+left_binsearch()+right_binsearch thus it will be in O(logn)

Here is the Code

Page 9: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

its running for may test cases Correct me if Anything WrongRun Here https://ideone.com/g7koI

run Here

ReplySandeep says:May 3, 2011 at 6:49 PM

@WgpShashank: Thanks for suggesting a new method. The approach looks fine,but the time complexity in worst case is O(n). Consider the case when allelements are same.

In this case, the time complexity can be written as

T(n) = 2*T(n/2) + C

which is O(n)

Reply

#include<stdio.h>int Count(int a[], int value, int low, int high){ int mid; if (high < low) return 0; mid = low + (high - low)/2; if (a[mid] > value) return Count(a, value, low, mid - 1); else if (a[mid] < value) return Count(a, value, mid + 1, high); else return 1 + Count(a, value, low, mid - 1) + Count(a, value, mid + 1, high);} int main(){ int a[] = {1, 2, 2, 3, 3, 3, 3}; int value = 3; printf("%d\n", Count(a, value, 0, sizeof(a)/sizeof(int)-1)); return 0;}

int a[] = {3, 3, 3, 3, 3, 3, 3};int value = 3;

Page 10: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

WgpShashank says:May 27, 2011 at 8:47 PM

@sandeep Thanks For Pointing out ..yes it will O(n) in this scenario

ReplyYogesh says:September 29, 2011 at 12:12 AM

i think that is the only case which is making its time complexityO(n)...

that can be covered by adding line

at the beginning of the count function

Correct me if i am wrong somewhere.

Replysaurabh says:February 4, 2012 at 4:35 PM

i think Time compl. will be O(logn)

Worst case will be longest height of above recursion tree....

let k will be max height.....and also we see terms at each level forms aG.P(1,1/2,1/4,...)and through calculas stuff we know this will be a convergence series....andsum of node at each level is n(n/2+n/2)....n(1/2)^k< =1k>=log2(n)..nearly....hence time compl will b O(logn)

Reply

Comment

if (a[high] == value && a[low] == value) return (high-low)+1

T(n) / \ T(n/2) T(n/2) / \ / \ T(n/4) T(n/4) T(n/4) T(n/4)...............................

Page 11: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

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: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

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: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

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: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

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

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: Count the Number of Occurrences in a Sorted Array _ GeeksforGeeks

5/12/12 Count the number of occurrences in a sorted array | GeeksforGeeks

15/15www.geeksforgeeks.org/archives/12164

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