Binary Search as Divide and Conquer in DSA Javascript - Time & Space Complexity
We want to understand how fast binary search finds a target in a sorted list.
How does the number of steps change as the list grows bigger?
Analyze the time complexity of the following code snippet.
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 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 value in a sorted array by repeatedly dividing the search range in half.
- Primary operation: Checking the middle element and adjusting the search range.
- How many times: The search range halves each time until the target is found or 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 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 like linear search."
[OK] Correct: Binary search skips half the list each step, so it does far fewer checks than linear search.
Understanding binary search time complexity shows you can analyze efficient algorithms that use smart dividing steps.
"What if the array was not sorted? How would the time complexity of searching change?"
Practice
Binary Search as a divide and conquer algorithm?Solution
Step 1: Understand divide and conquer in binary search
Binary search splits the array into two halves and decides which half to search next.Step 2: Identify the repeated halving process
It keeps dividing the search space by half until the target is found or no elements remain.Final Answer:
It repeatedly divides the search interval in half to find the target value. -> Option CQuick Check:
Divide and conquer = halve search space [OK]
- Thinking binary search checks every element
- Confusing binary search with linear search
- Assuming binary search sorts the array
arr between indices low and high in JavaScript?Solution
Step 1: Understand middle index calculation
The middle index should be an integer, so we use Math.floor to round down.Step 2: Check each option
const mid = (low + high) / 2; returns a float, const mid = Math.floor((low + high) / 2); correctly floors the average, const mid = Math.ceil((low + high) / 2); rounds up which can cause errors, const mid = low + high / 2; has wrong operator precedence.Final Answer:
const mid = Math.floor((low + high) / 2); -> Option DQuick Check:
Use Math.floor to get integer mid [OK]
- Not flooring the middle index causing float errors
- Using wrong operator precedence without parentheses
- Using Math.ceil which can skip elements
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
const nums = [2, 4, 6, 8, 10];
console.log(binarySearch(nums, 6));Solution
Step 1: Trace the binary search for target 6
Initial low=0, high=4, mid=2 (element 6). arr[mid] equals target, so return 2.Step 2: Confirm returned index
The function returns index 2 where 6 is found.Final Answer:
2 -> Option AQuick Check:
Target 6 found at index 2 [OK]
- Confusing index with value
- Off-by-one errors in mid calculation
- Returning value instead of index
function binarySearch(arr, target) {
let low = 0;
let high = arr.length;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}Solution
Step 1: Check high initialization
High should be last index, which is arr.length - 1, not arr.length (out of bounds).Step 2: Confirm fix
Changing high to arr.length - 1 prevents accessing undefined elements and infinite loop.Final Answer:
Change high initialization to arr.length - 1 -> Option BQuick Check:
High = arr.length - 1 fixes index error [OK]
- Setting high to arr.length causing out-of-bounds
- Changing while condition incorrectly
- Returning value instead of index
arr = [1, 3, 3, 5, 7, 7, 7, 9]. Using binary search as divide and conquer, which index will be returned when searching for 7 with the standard binary search implementation below?function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}Choose the correct index returned and explain why.
Solution
Step 1: Trace binary search on duplicates
Initial low=0, high=7, mid=3 (arr[3]=5 < 7), so low=4. Next mid=5 (arr[5]=7), matches target, returns 5 immediately.Step 2: Understand standard binary search behavior
Standard binary search returns the first found match, not necessarily first or last occurrence.Final Answer:
5 (middle occurrence of 7) -> Option AQuick Check:
Standard binary search returns any matching index [OK]
- Assuming it always returns first or last occurrence
- Ignoring duplicates in array
- Expecting -1 when target exists
Ready to prove it?
Pass the test and this pattern moves unknown
