Frequency in a Sorted Array Problem Statement

Given a sorted array ARR and a number X, your task is to determine the count of occurrences of X within ARR.

Note:

  • If X is not found in the array, return 0.
  • The array is sorted in non-decreasing order.

Input Format:

The first line contains an integer ‘T’ representing the number of test cases. Each test case includes two subsequent parts:

1. An integer N representing the size of the input array.
2. A line of N integers denoting the elements of the array.
3. A single integer X for which you need to find occurrences.

Output Format:

For each test case, output a single line containing an integer representing the number of times the target element X appears in the array.

Follow Up:

Try to implement a solution with O(log(N)) time complexity and O(1) space complexity.

Constraints:

  • 1 ≤ T ≤ 102
  • 1 ≤ N ≤ 104
  • 0 ≤ ARR[i], X ≤ 109
  • Time Limit: 1 sec

Special Note:

Your task is to implement the specified function, and you are not required to manage any input or output operations.
AnswerBot
8d

Count occurrences of a number in a sorted array efficiently.

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

  • Calculate the count of occurrences by subtracting ...read more

Help your peers!
Add answer anonymously...
Urban Company 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

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