Update appNew update is available. Click here to update.

Occurrence of X in a Sorted Array

Last Updated: 22 Jul, 2020
Difficulty: Easy


Try Problem

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.
You are not required to print the expected output, it has already been taken care of. Just implement the function. 
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

Approach 1

  • 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 1 if the element being visited is X.
  • Once all the elements have been visited, we can return the count.
Try Problem