Challenge - 5 Problems
Binary Search Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Binary Search for Existing Element
What is the output of the following code when searching for the number 7 in the list?
DSA Python
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 arr = [1, 3, 5, 7, 9, 11] print(binary_search(arr, 7))
Attempts:
2 left
💡 Hint
Remember that list indices start at 0 and the list is sorted.
✗ Incorrect
The number 7 is at index 3 in the list. The binary search finds it and returns the index.
❓ Predict Output
intermediateOutput When Element is Not Present
What will the code print when searching for the number 7 in the list?
DSA Python
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 arr = [2, 4, 6, 8, 10] print(binary_search(arr, 7))
Attempts:
2 left
💡 Hint
If the element is not found, the function returns -1.
✗ Incorrect
Since 7 is not in the list, the function returns -1.
🧠 Conceptual
advancedWhy Use Iterative Binary Search Instead of Recursive?
Which of the following is the best reason to prefer iterative binary search over recursive binary search?
Attempts:
2 left
💡 Hint
Think about what happens with function calls in recursion.
✗ Incorrect
Recursive calls add overhead to the call stack, which uses more memory. Iterative approach avoids this.
❓ Predict Output
advancedOutput of Binary Search with Duplicate Elements
What index will the binary search return when searching for 5 in the list with duplicates?
DSA Python
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 arr = [1, 3, 5, 5, 5, 7, 9] print(binary_search(arr, 5))
Attempts:
2 left
💡 Hint
Binary search may return any index where the target is found.
✗ Incorrect
The binary search returns index 3 where 5 is found.
🔧 Debug
expertIdentify the Bug in Binary Search Implementation
What error will this code produce when searching for 15 in the list?
DSA Python
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left < right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 arr = [5, 7, 10, 15] print(binary_search(arr, 15))
Attempts:
2 left
💡 Hint
Check the loop condition carefully and think about when the loop stops.
✗ Incorrect
The loop condition 'left < right' causes the loop to stop before checking when left == right. Here, it returns -1 even though 15 is present at index 3.
