Challenge - 5 Problems
Binary Search Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this binary search code?
Consider the following Python code that performs binary search on a sorted list. What will be printed after running it?
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 nums = [2, 4, 6, 8, 10, 12, 14] print(binary_search(nums, 10))
Attempts:
2 left
💡 Hint
Remember that list indices start at 0 and the list is sorted.
✗ Incorrect
The list is [2, 4, 6, 8, 10, 12, 14]. The target 10 is at index 4 (0-based). The binary search returns the index where the target is found.
🧠 Conceptual
intermediateWhy must the list be sorted for binary search?
Why is it necessary for the list to be sorted before applying binary search?
Attempts:
2 left
💡 Hint
Think about how binary search decides which half of the list to ignore.
✗ Incorrect
Binary search relies on the order of elements to eliminate half of the search space each time. If the list is not sorted, this logic breaks down.
❓ Predict Output
advancedWhat is the output of this code with an unsorted list?
What will this code print when performing binary search on an unsorted 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 nums = [10, 2, 14, 4, 6, 12, 8] print(binary_search(nums, 10))
Attempts:
2 left
💡 Hint
The list is not sorted. Think about how binary search behaves in this case.
✗ Incorrect
The list is unsorted, so binary search cannot reliably find the target. It may miss the target even if it exists, returning -1.
🔧 Debug
advancedWhat error does this binary search code produce?
What error will this code raise when run?
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 nums = [1, 3, 5, 7, 9] print(binary_search(nums, 5))
Attempts:
2 left
💡 Hint
Check the if statement syntax carefully.
✗ Incorrect
The if statement is missing a colon at the end, causing a SyntaxError.
🚀 Application
expertHow many comparisons does binary search make to find 15 in this list?
Given the sorted list [3, 6, 9, 12, 15, 18, 21, 24], how many comparisons will binary search make to find the target 15?
Attempts:
2 left
💡 Hint
Count each time the code compares the target with the middle element.
✗ Incorrect
Binary search compares the target with the middle element each iteration. For this list, it takes 3 comparisons to find 15.
