Number of occurrence | Practice | GeeksforGeeks

Given a sorted array Arr of size N and a number X, you need to find the number of occurrences of X in Arr.
Example 1:
Input:
N = 7, X = 2
Arr[] = {1, 1, 2, 2, 2, 2, 3}
Output: 4
Explanation: 2 occurs 4 times in the
given array.
Example 2:
Input:
N = 7, X = 4
Arr[] = {1, 1, 2, 2, 2, 2, 3}
Output: 0
Explanation: 4 is not present in the
given array.
Your Task:
You don't need to read input or print anything. Your task is to complete the function count() which takes the array of integers arr, n and x as parameters and returns an integer denoting the answer.
Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 105
1 ≤ Arr[i] ≤ 106
1 ≤ X ≤ 106
 
0
mehtay0374 days ago
Python Solution:
 
class Solution:
def count(self,arr, n, x): # code here count=0 for i in range(n):     if(x==arr[i]):         count+=1 return count     
+1
harshscode5 days ago
   int cnt=0;  for(int i=0;i<n;i++)  {      if(a[i]==x)      cnt++;  }  return cnt;
-1
shubhamshrivas15 days ago
 def count(self,arr, n, x): # code here if x not in arr:     return 0 c=0 for i in arr:     if i==x:         c+=1       return c   
-1
radhikamendiratta19945 days ago
#python binary search till mid==x and then loop backward from mid to find x_start_ind and forward from mid to find x_end_ind
 def count(self,arr, n, x):
		start = 0
		end = n-1
		x_start = 0
		x_end = 0
		mid = (end-start)//2
		while start<=end:
		    if arr[mid]<x:
		        start = mid+1
		        mid = ((end-start)//2)+start
		    elif arr[mid]>x:
		        end = mid-1
		        mid = ((end-start)//2)+start
		    elif arr[mid]==x:
		        break
		for i in range(mid,-1,-1):
		    if arr[0]==x:
                x_start=0
                break
		    if arr[i]!=x:
		        x_start = i+1
		        break
		for i in range(mid,n):
		    if arr[n-1]==x:
                x_end=n-1
                break
		    if arr[i]!=x:
		        x_end = i-1
		        break
		return (x_end-x_start+1) if x_end>=x_start else 0
+1
harshscode1 week ago
 int cnt=0;   int i=0;   while(i<n)   {       if(a[i]==x)       break;       i++;   }   while(a[i]==x and i<n)   {       cnt++;       i++;   }      return cnt;    
0
mestryruturaj1 week ago
Java: Binary search
class Solution {
    int count(int[] arr, int n, int x) {
        int res = 0;
        int left = 0;
        int right = n-1;
        boolean found = false;
        
        while (left <= right) {
            int middle = (right + left) / 2;
            
            if (arr[middle] == x) {
                found = true;
                
                while (middle >= 0 && arr[middle] == x) {
                    middle--;
                }
                left = middle + 1;
                break;
            }
            else if (arr[middle] < x) {
                left = middle + 1;
            }
            else {
                right = middle - 1;
            }
        }
        
        if (!found) return 0;
        else {
            while(left < n && arr[left] == x) {
                res++;
                left++;
            }
        }
        return res;
        
    }
}
0
navins2 weeks ago
PYTHON CODE:
 
def count(self,arr, n, x): # code here count=0 i=0              for i in range (n):           if (arr[i]==x):               break       while i<n and arr[i]==x:           count+=1           i+=1                  return count
0
csearvind17212 weeks ago
O(logN) sOlution...
int firstOccur(int arr[], int n, int target)    {       int low = 0, high = n-1;       while(low<=high)       {            int mid = (low+high)/2;           if(arr[mid]<target) low = mid+1;           else if(arr[mid]>target) high = mid-1;           else            {               if(mid==0 || arr[mid-1]!=target)               {                   return mid;               }               else               {                   high = mid-1;               }           }       }       return -1;   }      int lastOccur(int arr[], int n, int target)    {       int low = 0, high = n-1;       //int mid = (low+high)/2;       while(low<=high)       {           int mid = (low+high)/2;           if(arr[mid]<target) low = mid+1;           else if(arr[mid]>target) high = mid-1;           else            {               if(mid==n-1 || arr[mid+1]!=target)               {                   return mid;               }               else               {                   low = mid+1;               }           }       }       return -1;   }int count(int arr[], int n, int x) {    int first = firstOccur(arr, n, x);    if(first == -1) return 0;    int last  = lastOccur(arr, n, x);    return last-first+1;}}; 
0
amrit_kumar2 weeks ago
C++ O(log n) binary search
 
int binarySearch(int arr[], int n, int x, bool flag)
    {
        int l = 0;
        int r = n-1;
        int result  = -1;
        while(l<=r)
        {
            int mid = l+(r-l)/2;
            if(arr[mid]==x)
            {
                result = mid;
                if(flag) r = mid-1;
                else l = mid+1;
            }
            else if (arr[mid]>x) r= mid-1;
            else l   = mid+1;
        }
        return result;
    }
	int count(int arr[], int n, int x) {
	    int left_oc = binarySearch(arr,n,x,true);
	    if(left_oc==-1) return 0;
	    int right_oc = binarySearch(arr,n,x,false);
	    return (right_oc-left_oc+1);
	}
+1
zerefkhan2 weeks ago
C++ solution
Total Time Taken:   0.28/1.5   
int count(int arr[], int n, int x) {
	    int occurence = 0,i=0;
	    for(; i < n; i++){
	        if(arr[i] == x) break;
	    }
	    while(arr[i]==x && i < n){occurence++;i++;}
	    return occurence;
	}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.