Occurrence of X in a Sorted Array.

You have been given a sorted array/list of integers of size N and an integer X. Find the total number of occurrences of X in the array/list.

Input Format
The first line of the input contains two integers N and X. They represent the size of the array/list and X respectively. 

The second line contains N single space-separated integer representing the array/list elements.
Output Format
The only line of output will print the total number of occurrences of X in the array/list.
Note:
You are not required to print the expected output, it has already been taken care of. Just implement the function. 
Constraints:
1 <= N <= 10^5
1 <= Arr[i] <= 10^9
Where Arr[i] represents the element i-th element in the array/list.

Time Limit: 1sec
CodingNinjas
author
2y
Simple Counting Approach
  • Initialize a count variable with 0 initially, to keep track of the total number of occurrences of X.
  • Visit every element one by one in the sorted array and increase the count by...read more
CodingNinjas
author
2y
Binary Search
  • Use binary search to find the first occurrence of X, say the index at which X is found be ‘xPos’.
  • If ‘xPos’ is -1, then X doesn’t exist in the array and hence we return 0.
  • But if it is not ...read more
CodingNinjas
author
2y
Smart Binary Search
  • Use Binary search to get an index of the first occurrence of X in the input Array. Say the index at which X appeared first as ‘xStartIndex’.
  • Use Binary search to get an index of the ...read more
Add answer anonymously...
Directi Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter