Frequency In A Sorted Array

You are given a sorted array 'ARR' and a number 'X'. Your task is to count the number of occurrences of 'X' in 'ARR'.

Note :
1. If 'X' is not found in the array, return 0.
2. The given array is sorted in non-decreasing order.
Input Format :
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.

The first line of each test case contains an integer ‘N’ representing the size of the input array.

The second line of each test case contains elements of the array separated by a single space.

The last line of each test case contains a single integer 'X'.
Output Format :
For each test case, the only line of output will contain a single integer which represents the number of occurrences of target element 'X' in the array.

Follow Up :

Try to solve it in O(log(N)) time and O(1) space.
Note :
You don't need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10^2
1 <= N <= 10^4
0 <= ARR[i], X <= 10^9

Time Limit : 1 sec
AnswerBot
1y

The task is to count the number of occurrences of a given number in a sorted array.

  • Use binary search to find the first and last occurrence of the given number in the array.

  • Subtract the indices of the ...read more

CodingNinjas
author
2y

1. Gave a map based solution asked me to optimize space and time
2. Gave a linear solution with a counter with no extra space
3. Gave a binary search based solution with upper bound and lower bound. The...read more

CodingNinjas
author
2y
Binary Search

The basic idea is to first find an occurrence of the target element ‘X’ using binary search. Then, we count the matches toward the left and right sides of the found index.

Binary Search: ...read more

CodingNinjas
author
2y
Linear Search

Linearly search for target element ‘X’, count the occurrences of ‘X’ and return the ‘COUNT’.

Linear search is a method for finding an element within a list/array. It sequentially checks e...read more

CodingNinjas
author
2y
Modified Binary Search

The basic idea is to first find the first and the last occurrence of the target element ‘X’ using binary search. Then, return the difference of these indexes +1, as this the coun...read more

Add answer anonymously...
Amazon Software Developer Intern 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