Challenge - 5 Problems
Binary Search Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Binary Search on Sorted Array
What is the output of the following Java code that performs binary search on a sorted array?
DSA Java
import java.util.Arrays; public class BinarySearchDemo { public static void main(String[] args) { Integer[] arr = {2, 4, 6, 8, 10, 12}; int index = Arrays.binarySearch(arr, 8); System.out.println(index); } }
Attempts:
2 left
💡 Hint
Remember that binarySearch returns the index of the element if found.
✗ Incorrect
The array is sorted in ascending order. The element 8 is at index 3 (0-based). So, binarySearch returns 3.
🧠 Conceptual
intermediateWhy Must the Array Be Sorted for Binary Search?
Why is it necessary for the array to be sorted before applying binary search?
Attempts:
2 left
💡 Hint
Think about how binary search decides which half to continue searching.
✗ Incorrect
Binary search compares the target with the middle element and decides to search left or right half. This logic only works if the array is sorted.
❓ Predict Output
advancedBinary Search Result on Unsorted Array
What will be the output of this Java code that performs binary search on an unsorted array?
DSA Java
import java.util.Arrays; public class BinarySearchUnsorted { public static void main(String[] args) { int[] arr = {2, 4, 10, 6, 12, 8}; int index = Arrays.binarySearch(arr, 8); System.out.println(index); } }
Attempts:
2 left
💡 Hint
Binary search on unsorted arrays returns a negative value indicating insertion point.
✗ Incorrect
Since the array is not sorted, binarySearch returns a negative value indicating the insertion point where 8 would be placed to keep order. The value -3 means insertion at index 2.
🔧 Debug
advancedFind the Bug in Binary Search Usage
Identify the problem in this Java code snippet that uses binary search on a sorted array.
DSA Java
import java.util.Arrays; public class BuggyBinarySearch { public static void main(String[] args) { int[] arr = {1, 3, 5, 7, 9}; int target = 4; int index = Arrays.binarySearch(arr, target); if (index >= 0) { System.out.println("Found at index " + index); } else { System.out.println("Not found"); } } }
Attempts:
2 left
💡 Hint
Check how binarySearch indicates found elements with index 0.
✗ Incorrect
binarySearch returns 0 if the target is at index 0. The condition index > 0 misses this case, so it should be index >= 0.
🚀 Application
expertUsing Binary Search to Find First Occurrence in Sorted Array with Duplicates
Given a sorted array with duplicates, which approach correctly finds the first occurrence index of a target using binary search?
Attempts:
2 left
💡 Hint
Think about how to find the leftmost target index, not just any occurrence.
✗ Incorrect
To find the first occurrence, binary search must continue searching the left half after finding the target, updating the result to the smallest index found.
