How often a number appears in a sorted array
Reported in interviews at (where)
nums is sorted from smallest to largest. Return how many times target appears in it.
Counting every element works in O(n). Can you do it in O(log n)?
- Input
nums = [1,2,2,2,5,9]
target = 2- Output
3
2 is at indexes 1, 2 and 3.
- Input
nums = [1,3,5]
target = 4- Output
0
4 is not there.
- Input
nums = [7,7,7]
target = 7- Output
3
Every element is the target.
Limits
1 <= nums.length <= 100000-1000000000 <= nums[i], target <= 1000000000nums is sorted in non-decreasing order
Hints
Hint 1
Find the first index whose value is at least target, and the first index whose value is greater than target. Both are binary searches.
Hint 2
The count is the difference between those two indexes.
Where this was reported
- Aditya Birla Group, SDE interview, 2023 (Code360)
Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.
Run your code to check it on the examples. Submit runs every hidden test.
