Problem Statement
Given a sorted array, write a function to count the number of occurrences of a target element using binary search. The function should return the number of times the target appears in the array.
Sample Test Case
Approaches
Brute Force Approach
Idea
- Traverse through the array, and count each occurrence of the target element by comparing each element with the target.
Steps
- Loop through the array.
- Compare each element with the target.
- Increment the count if the element equals the target.
- Return the count after completing the loop.
Time Complexity
- O(n) where
n is the length of the array.
Space Complexity
Example Code
Dry Run
- Input: nums = [1, 2, 2, 2, 3, 4, 5], target = 2
- Initialize count = 0.
- Loop through the array:
- At index 1: 2 == 2, increment count.
- At index 2: 2 == 2, increment count.
- At index 3: 2 == 2, increment count.
- Output: count = 3.
Efficient Approach (Binary Search)
Idea
- Use binary search to find the first and last occurrences of the target. The number of occurrences will be the difference between the indices of the last and first occurrences plus one.
Steps
- Perform binary search to find the first occurrence of the target.
- Perform binary search to find the last occurrence of the target.
- Return the difference between the indices of the last and first occurrences, plus one.
Time Complexity
- O(log n) due to binary search.
Space Complexity
Example Code
Dry Run
- Input: nums = [1, 2, 2, 2, 3, 4, 5], target = 2
- First occurrence:
low = 0, high = 6, mid = 3 (nums[3] = 2), first = 3, continue searching left.
low = 0, high = 2, mid = 1 (nums[1] = 2), first = 1, stop.
- Last occurrence:
low = 0, high = 6, mid = 3 (nums[3] = 2), last = 3, continue searching right.
low = 4, high = 6, mid = 5 (nums[5] = 4), stop.
- Occurrences = last - first + 1 = 3.
Example Test Case
Complexity Analysis
Brute Force Approach
- Time Complexity: O(n)
- Space Complexity: O(1)
Efficient Approach
- Time Complexity: O(log n)
- Space Complexity: O(1)
Conclusion
- The brute force approach has a linear time complexity, which is not optimal for large arrays.
- The binary search approach reduces the time complexity to logarithmic, making it more efficient for larger arrays.