Binary Search as Divide and Conquer in DSA Java - Time & Space Complexity
We want to understand how fast binary search finds an item in a sorted list.
How does the number of steps change as the list gets bigger?
Analyze the time complexity of the following code snippet.
public int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
This code searches for a target number in a sorted array by repeatedly dividing the search range in half.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the middle element of the current search range.
- How many times: The search range halves each time, so this check repeats until the range is empty.
Each step cuts the list size in half, so the number of steps grows slowly as the list grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 checks |
| 100 | About 7 checks |
| 1000 | About 10 checks |
Pattern observation: Doubling the list size adds only one extra step.
Time Complexity: O(log n)
This means the number of steps grows slowly, adding just one step when the list size doubles.
[X] Wrong: "Binary search checks every element one by one like linear search."
[OK] Correct: Binary search skips half the list each time, so it does far fewer checks than linear search.
Understanding binary search time complexity shows you can analyze efficient algorithms, a key skill in coding interviews.
"What if the array was not sorted? How would that affect the time complexity of searching for a target?"
Practice
Binary Search as a divide and conquer algorithm?Solution
Step 1: Understand divide and conquer in binary search
Binary search splits the sorted array into two halves and decides which half to continue searching in.Step 2: Eliminate half the search space
By comparing the middle element with the target, it discards one half, reducing the problem size quickly.Final Answer:
It divides the search space into two halves and eliminates one half each time. -> Option BQuick Check:
Divide and conquer = split and discard half [OK]
- Thinking binary search checks every element
- Confusing binary search with sorting
- Believing binary search adds elements
Solution
Step 1: Check method signature correctness
public static int binarySearch(int[] arr, int target) uses public static, returns int index, and has correct parameter types and order.Step 2: Compare other options
int binarySearch(int arr[], target) misses access modifier and parameter type for target; public int binarySearch(int[] arr, int target, int start, int end) has extra parameters but no static; static void binarySearch(int[] arr, int target) returns void which is incorrect for search.Final Answer:
public static int binarySearch(int[] arr, int target) -> Option AQuick Check:
Correct signature returns int and uses static [OK]
- Omitting static keyword
- Wrong return type (void instead of int)
- Missing parameter types
int[] arr = {2, 4, 6, 8, 10};
int target = 6;
int result = binarySearch(arr, target);
System.out.println(result);
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}Solution
Step 1: Identify the target and array
The array is [2,4,6,8,10], target is 6.Step 2: Trace binary search steps
Initial left=0, right=4, mid=2; arr[2]=6 equals target, so return 2.Final Answer:
2 -> Option AQuick Check:
Index of 6 in array = 2 [OK]
- Confusing index with value
- Off-by-one errors in mid calculation
- Returning wrong index when target found
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}Solution
Step 1: Identify array bounds usage
Right is set to arr.length, which is out of array index range (max index is length-1).Step 2: Fix right boundary
Set right = arr.length - 1 to prevent accessing invalid index and avoid runtime error.Final Answer:
Change right to arr.length - 1 to avoid ArrayIndexOutOfBoundsException. -> Option CQuick Check:
Array indices go from 0 to length-1 [OK]
- Setting right to arr.length causes index error
- Incorrect mid calculation
- Changing loop condition incorrectly
int[] arr = {1, 2, 2, 2, 3, 4}. How would you modify binary search to find the first occurrence of the target 2?Solution
Step 1: Understand duplicate handling in binary search
Standard binary search returns any matching index, not necessarily first occurrence.Step 2: Modify search to find first occurrence
When target found, move right pointer to mid-1 to continue searching left side for earlier matches.Final Answer:
After finding target, continue searching left half to find earlier occurrence. -> Option DQuick Check:
Find first occurrence by searching left after match [OK]
- Stopping at first found index
- Using linear search unnecessarily
- Changing mid calculation without reason
Ready to prove it?
Pass the test and this pattern moves unknown
