Recall & Review
beginner
What is the main advantage of using a sorted array to count occurrences of an element?
A sorted array allows us to use binary search to find the first and last positions of the element efficiently, reducing the time complexity from linear to logarithmic.
Click to reveal answer
beginner
Explain how binary search helps in counting occurrences of an element in a sorted array.
Binary search finds the first and last index of the element quickly. The count is the difference between these two indices plus one.
Click to reveal answer
intermediate
What is the time complexity of counting occurrences of an element in a sorted array using binary search?
O(log n), where n is the number of elements in the array, because binary search is used twice.
Click to reveal answer
beginner
If the element is not present in the sorted array, what should the count be?
The count should be 0 because the element does not appear in the array.
Click to reveal answer
intermediate
Describe the steps to find the first occurrence of an element using binary search.
1. Set start and end pointers.<br>2. Find mid index.<br>3. If mid element equals target, move end to mid - 1 to find earlier occurrence.<br>4. If mid element is less than target, move start to mid + 1.<br>5. Repeat until start > end.<br>6. The first occurrence is at start if element matches.
Click to reveal answer
What is the first step to count occurrences of an element in a sorted array?
✗ Incorrect
Using binary search to find the first and last positions is efficient and leverages the sorted property.
If the first occurrence of an element is at index 3 and the last occurrence is at index 7, what is the count of that element?
✗ Incorrect
Count = last index - first index + 1 = 7 - 3 + 1 = 5.
What is the time complexity of counting occurrences using binary search in a sorted array of size n?
✗ Incorrect
Binary search runs in O(log n), and we do it twice, so overall O(log n).
What should be returned if the element is not found in the sorted array?
✗ Incorrect
Count of occurrences is zero if the element is not present.
Which of these is NOT a step in finding the first occurrence of an element using binary search?
✗ Incorrect
If mid element equals target, we move end to mid - 1 to find earlier occurrence, not mid + 1.
Describe how to count the occurrences of an element in a sorted array using binary search.
Think about how binary search can find boundaries efficiently.
You got /4 concepts.
Explain why counting occurrences in a sorted array is faster with binary search than linear search.
Compare how many elements each method checks.
You got /4 concepts.