FastPrepCount Occurrences in a Sorted Array
Problems/Count Occurrences in a Sorted Array

Count Occurrences in a Sorted Array

Adobe logoAdobe● EasyFULLTIMEPHONE SCREENONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interviewer asked: "sorted array, find #occurrences of element x, have to write binary search from scratch, the lower_bound and upper_bound."

The report does not give input bounds or examples. Here, the array has up to 10^5 values and the answer is a plain count. The judge checks only the count, so it cannot tell whether you used binary search.

The judged task matches the report at about 95%.

You are given an integer array nums sorted in non-decreasing order and an integer x. Return how many times x appears in nums.

Write the binary search yourself: find the first position whose value is at least x (the lower bound) and the first position whose value is greater than x (the upper bound). Your solution should run in O(log n) time.

Function

countOccurrences(nums: int[], x: int) → int

Examples

Example 1

nums = [1,2,2,2,3,5]x = 2return = 3

The first value that is at least 2 is at index 1, and the first value greater than 2 is at index 4. So 2 appears 4 - 1 = 3 times.

Example 2

nums = [1,3,5,7]x = 4return = 0

Both bounds land on index 2, the position of 5, because no value equals 4. The answer is 0.

Example 3

nums = [-4,-4,-4]x = -4return = 3

Every element equals -4. The lower bound is 0 and the upper bound is 3, the array length, so the answer is 3.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i], x <= 10^9
  • nums is sorted in non-decreasing order.

More Adobe problems

  • Evaluate a Parenthesized Integer ExpressionPHONE SCREEN · Seen Oct 2026
  • All Elements of Two BSTs in OrderPHONE SCREEN · Seen Aug 2026
  • Rotate an Array In PlaceOA · PHONE SCREEN · Seen Aug 2026
All Adobe interview questionsSee Adobe hiring insights
Saved
public int countOccurrences(int[] nums, int x) {
    // Write your code here.
}
Checking account…