Binary Search Recursive Approach in DSA Java - Time & Space Complexity
We want to understand how the time taken by recursive binary search changes as the input size grows.
Specifically, how many steps does it take to find a number in a sorted list?
Analyze the time complexity of the following code snippet.
public int binarySearch(int[] arr, int target, int left, int right) {
if (left > right) {
return -1; // not found
}
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
return binarySearch(arr, target, left, mid - 1);
} else {
return binarySearch(arr, target, mid + 1, right);
}
}
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: Recursive call that halves the search range each time.
- How many times: The search range is cut in half until the target is found or range is empty.
Each step cuts the problem size roughly in half, so the number of steps grows slowly as input size grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 steps |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: Doubling the input size adds only one extra step.
Time Complexity: O(log n)
This means the number of steps grows slowly, increasing by one step each time the input size doubles.
[X] Wrong: "Binary search checks every element one by one, so it is O(n)."
[OK] Correct: Binary search does not check all elements; it splits the search range in half each time, so it only needs a few steps even for large inputs.
Understanding binary search time complexity shows you can analyze efficient searching methods, a key skill in many coding challenges and real-world problems.
"What if we changed the recursive binary search to an iterative version? How would the time complexity change?"
Practice
binary search recursive approach when searching for a value in a sorted array?Solution
Step 1: Understand binary search logic
Binary search works by dividing the sorted array into two halves and deciding which half to search next based on comparison.Step 2: Apply recursion in binary search
The recursive approach calls the same function on the half where the target value could be, reducing the search space each time.Final Answer:
Divide the array into halves and search recursively in the half where the value may exist -> Option CQuick Check:
Binary search = divide and conquer [OK]
- Thinking binary search checks every element
- Not using recursion or iteration to reduce search space
- Assuming array is unsorted
Solution
Step 1: Identify base case for recursion end
The base case ends recursion when the search space is invalid, i.e., start index is greater than end index.Step 2: Confirm correct base case syntax
Usingif (start > end) return -1;correctly signals the target is not found.Final Answer:
if (start > end) return -1; -> Option DQuick Check:
Base case = start > end [OK]
- Using start == end as base case incorrectly
- Returning wrong index when target not found
- Confusing base case with target found condition
public class Test {
public static int binarySearch(int[] arr, int start, int end, int target) {
if (start > end) return -1;
int mid = start + (end - start) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] > target) return binarySearch(arr, start, mid - 1, target);
else return binarySearch(arr, mid + 1, end, target);
}
public static void main(String[] args) {
int[] data = {2, 4, 6, 8, 10};
System.out.println(binarySearch(data, 0, data.length - 1, 6));
}
}Solution
Step 1: Trace initial call and mid calculation
Array is [2,4,6,8,10], start=0, end=4, target=6. Mid = 0 + (4-0)/2 = 2.Step 2: Check if arr[mid] equals target
arr[2] = 6 equals target 6, so return mid = 2.Final Answer:
2 -> Option AQuick Check:
Target found at index 2 [OK]
- Miscomputing mid index
- Returning wrong index when target found
- Confusing array indices
public static int binarySearch(int[] arr, int start, int end, int target) {
if (start >= end) return -1;
int mid = (start + end) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] > target) return binarySearch(arr, start, mid - 1, target);
else return binarySearch(arr, mid + 1, end, target);
}Solution
Step 1: Analyze base case condition
Base case currently isif (start >= end) return -1;. This causes missing the case when start == end and target is at that index.Step 2: Correct base case to allow checking when start == end
Changing toif (start > end) return -1;ensures the single element at start==end is checked.Final Answer:
Base case condition should be start > end, not start >= end -> Option AQuick Check:
Base case must allow start == end check [OK]
- Using >= instead of > in base case
- Ignoring single element check
- Incorrect mid calculation
Solution
Step 1: Understand duplicates and first occurrence
Duplicates mean target can appear multiple times. To find first occurrence, we must check if earlier indices also have target.Step 2: Modify recursive call when target found
Whenarr[mid] == target, recursively search left half to find if target appears earlier. If none found, return current mid.Final Answer:
When arr[mid] == target, continue searching left half to find earlier occurrence -> Option BQuick Check:
Search left half on match for first occurrence [OK]
- Returning first found index without checking left side
- Searching right half on match
- Using linear search unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
