Binary Search Iterative Approach in DSA Javascript - Time & Space Complexity
We want to understand how the time taken by binary search changes as the list size grows.
How many steps does it take to find a number in a sorted list?
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 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 slowly, only increasing by one each time the input size doubles.
[X] Wrong: "Binary search checks every item one by one, so it is O(n)."
[OK] Correct: Binary search does not check every item; it cuts the search area in half each time, so it needs far fewer steps.
Understanding binary search time helps you explain efficient searching in sorted data, a key skill in many coding challenges.
"What if the array was not sorted? How would the time complexity of searching change?"
Practice
binary search iterative approach in a sorted array?Solution
Step 1: Understand binary search goal
Binary search aims to find a target value's position quickly in a sorted array by dividing the search space repeatedly.Step 2: Identify the iterative approach
The iterative method uses a loop to narrow down the search range until the target is found or the range is empty.Final Answer:
To find the position of a target value efficiently by repeatedly dividing the search interval in half -> Option BQuick Check:
Binary search = efficient position search [OK]
- Confusing binary search with sorting algorithms
- Thinking it works on unsorted arrays
- Assuming it finds maximum or minimum values
mid index in an iterative binary search in JavaScript?Solution
Step 1: Understand index calculation
Mid index must be an integer index, so we use Math.floor to round down the average of start and end.Step 2: Check options for correct syntax
const mid = Math.floor((start + end) / 2); uses Math.floor((start + end) / 2), which correctly calculates the middle index as an integer.Final Answer:
const mid = Math.floor((start + end) / 2); -> Option CQuick Check:
Mid index = Math.floor average [OK]
- Using division without floor, resulting in float index
- Using Math.ceil which can cause out-of-range index
- Adding start and end without division
function binarySearch(arr, target) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
const mid = Math.floor((start + end) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) start = mid + 1;
else end = mid - 1;
}
return -1;
}
console.log(binarySearch([2, 4, 6, 8, 10], 6));Solution
Step 1: Trace the binary search steps
Array is [2,4,6,8,10], target is 6. Initial start=0, end=4, mid=2. arr[2] = 6 matches target.Step 2: Return index when found
Since arr[mid] equals target, function returns mid = 2 immediately.Final Answer:
2 -> Option AQuick Check:
Target 6 found at index 2 [OK]
- Confusing index with value
- Off-by-one errors in start/end updates
- Returning value instead of index
function binarySearch(arr, target) {
let start = 0;
let end = arr.length - 1;
while (start < end) {
const mid = Math.floor((start + end) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) start = mid + 1;
else end = mid - 1;
}
return -1;
}Solution
Step 1: Analyze loop condition impact
The loop uses start < end, which misses the case when start equals end, possibly skipping the last element check.Step 2: Correct loop condition for full search
Changing to start <= end ensures the loop checks all elements including when start equals end.Final Answer:
The loop condition should be start <= end instead of start < end -> Option AQuick Check:
Loop condition must include equality [OK]
- Using < excludes last element check
- Changing mid calculation unnecessarily
- Returning value instead of index
function binarySearchFirst(arr, target) {
let start = 0;
let end = arr.length - 1;
let result = -1;
while (start <= end) {
const mid = Math.floor((start + end) / 2);
if (arr[mid] === target) {
result = mid;
end = mid - 1; // Continue searching left
} else if (arr[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return result;
}Solution
Step 1: Understand duplicate handling
To find first occurrence, we must not stop at first match but continue searching left side.Step 2: Use result variable and adjust end pointer
Store current match index in result, then move end to mid - 1 to search left side for earlier occurrence.Final Answer:
Keep track of found index and continue searching left by moving end to mid - 1 -> Option DQuick Check:
Track index + search left for first occurrence [OK]
- Stopping search immediately on first match
- Searching right side instead of left
- Ignoring duplicates in binary search
Ready to prove it?
Pass the test and this pattern moves unknown
