Binary Search Iterative Approach in DSA Java - Time & Space Complexity
We want to understand how the time taken by binary search changes as the list 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 = 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: The while loop that halves the search range each time.
- How many times: The loop runs until the search range is empty, roughly halving the range each step.
Each step cuts the search area in half, so the number of steps grows slowly as the list gets bigger.
| 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 steps needed grow very slowly compared to the size of the list.
[X] Wrong: "Binary search checks every element one by one, so it is O(n)."
[OK] Correct: Binary search does not check every element; it cuts the search space in half each time, so it needs far fewer steps.
Understanding binary search time complexity shows you can analyze efficient searching methods, a key skill in many coding challenges.
"What if the array was not sorted? How would the time complexity of searching change?"
Practice
mid variable in the iterative binary search algorithm?Solution
Step 1: Understand the role of
Themidin binary searchmidvariable calculates the middle index betweenlowandhighpointers to split the search range.Step 2: Purpose of
It helps decide whether to search the left or right half by comparing the middle element with the target.midFinal Answer:
To find the middle index of the current search range -> Option AQuick Check:
mid= middle index [OK]
- Confusing mid with target value
- Thinking mid counts iterations
- Assuming mid stores final answer
mid in an iterative binary search to avoid integer overflow?Solution
Step 1: Understand integer overflow risk
Addinglowandhighdirectly can exceed integer limits if both are large.Step 2: Safe calculation method
Usinglow + (high - low) / 2prevents overflow by subtracting before adding.Final Answer:
mid = low + (high - low) / 2 -> Option AQuick Check:
Safe mid calculation avoids overflow [OK]
- Using (low + high)/2 causing overflow
- Using subtraction incorrectly
- Multiplying low and high
int[] arr = {2, 4, 6, 8, 10};
int target = 6;
int low = 0, high = arr.length - 1;
int result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
result = mid;
break;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
System.out.println(result);Solution
Step 1: Trace the binary search steps
Initial low=0, high=4, mid=2. arr[2]=6 equals target 6, so result=2 and loop breaks.Step 2: Output the result
Result is 2, which is the index of target 6 in the array.Final Answer:
2 -> Option CQuick Check:
Index of 6 in arr = 2 [OK]
- Confusing index with value
- Not breaking loop on match
- Incorrect mid calculation
int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}Solution
Step 1: Analyze loop condition
The conditionlow < highmisses the case when low equals high, possibly skipping the last element.Step 2: Correct loop condition
Changing tolow <= highensures the last element is checked.Final Answer:
Change while condition to low <= high -> Option DQuick Check:
Loop must include low == high [OK]
- Using < instead of <= in loop
- Incorrect mid calculation
- Returning wrong index on failure
Solution
Step 1: Understand duplicates in binary search
Standard binary search returns any matching index, not necessarily the first occurrence.Step 2: Modify search to find first occurrence
Whenarr[mid] == target, storemidas potential answer and continue searching left by settinghigh = mid - 1.Final Answer:
When arr[mid] == target, update result and move high to mid - 1 -> Option BQuick Check:
Move left on match to find first occurrence [OK]
- Returning immediately on first match
- Moving right on match
- Ignoring duplicates
Ready to prove it?
Pass the test and this pattern moves unknown
