How can binary search be modified to find the first occurrence of a target value
Practice Questions
Q1
How can binary search be modified to find the first occurrence of a target value in a sorted array with duplicates?
Use a linear search
Modify the mid-point logic
Use a stack
Use a queue
Questions & Step-by-Step Solutions
How can binary search be modified to find the first occurrence of a target value in a sorted array with duplicates?
Step 1: Start with two pointers, 'left' at the beginning of the array and 'right' at the end of the array.
Step 2: While 'left' is less than or equal to 'right', calculate the 'mid' index as (left + right) / 2.
Step 3: Check if the value at 'mid' is equal to the target value.
Step 4: If it is equal, store the 'mid' index as a potential result and move the 'right' pointer to 'mid - 1' to continue searching in the left half.
Step 5: If the value at 'mid' is less than the target, move the 'left' pointer to 'mid + 1'.
Step 6: If the value at 'mid' is greater than the target, move the 'right' pointer to 'mid - 1'.
Step 7: Repeat steps 2 to 6 until 'left' is greater than 'right'.
Step 8: If a potential result was found, return it; otherwise, return -1 to indicate the target is not in the array.
Binary Search Modification – Understanding how to adjust the binary search algorithm to locate the first occurrence of a target value in a sorted array that contains duplicates.
Mid-point Logic Adjustment – Recognizing the need to modify the mid-point logic to continue searching in the left half of the array even after finding the target value.