Expecting binary search to count all duplicates directly
5. Given a sorted array arr that may contain multiple occurrences of target, how can you efficiently count the occurrences if the array is very large and you want to minimize the number of comparisons?
hard
A. Use a hash map to store counts of all elements
B. Use a linear scan from start to end counting matches
C. Sort the array first, then count occurrences
D. Use two binary searches to find first and last occurrence, then subtract indices
Solution
Step 1: Understand the problem constraints
Array is sorted and large, so linear scan is costly and sorting again is unnecessary.
Step 2: Apply binary search twice
Use binary search to find the first occurrence index and last occurrence index of target efficiently.
Step 3: Calculate count
Count = last occurrence index - first occurrence index + 1, minimizing comparisons.
Final Answer:
Use two binary searches to find first and last occurrence, then subtract indices -> Option D
Quick Check:
Two binary searches = efficient counting [OK]
Hint: Find first and last index with binary search [OK]
Common Mistakes:
Using linear scan on large arrays
Sorting already sorted array again
Using extra memory unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.