Binary Search Iterative Approach in DSA Typescript - 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.
function binarySearch(arr: number[], target: number): number {
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 (loop iterations) |
|---|---|
| 10 | About 4 |
| 100 | About 7 |
| 1000 | About 10 |
Pattern observation: Doubling the input size adds only one more step to the search.
Time Complexity: O(log n)
This means the search steps grow slowly, adding just one step each time the list size doubles.
[X] Wrong: "Binary search checks every element one by one, so it is O(n)."
[OK] Correct: Binary search skips half the list each step, so it does not check every element, making it much faster than linear search.
Understanding binary search time complexity shows you can analyze efficient algorithms, a key skill in problem solving and coding interviews.
"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 the goal of binary search
Binary search is used to find a target value in a sorted array by dividing the search space repeatedly.Step 2: Identify the iterative approach
The iterative approach 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 DQuick Check:
Binary search = efficient target search [OK]
- Confusing binary search with sorting algorithms
- Thinking binary search works on unsorted arrays
- Assuming it finds max/min values
Solution
Step 1: Understand index calculation in binary search
The middle index must be an integer index, so we use Math.floor to round down the division result.Step 2: Check each option
const mid = (low + high) / 2; returns a float, const mid = Math.floor((low + high) / 2); correctly floors the value, const mid = Math.ceil((low + high) / 2); rounds up which can cause errors, const mid = low + high; sums indices without division.Final Answer:
const mid = Math.floor((low + high) / 2); -> Option BQuick Check:
Use Math.floor for middle index [OK]
- Using division without flooring causing float index
- Using ceil which may skip elements
- Adding indices without dividing
function binarySearch(arr: number[], target: number): number {
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 result = binarySearch([2, 4, 6, 8, 10], 6);
console.log(result);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 output
Function returns index 2, which is printed.Final Answer:
2 -> Option AQuick Check:
Target 6 found at index 2 [OK]
- Off-by-one errors in index calculation
- Returning wrong index when target found
- Confusing return value with element value
function binarySearch(arr: number[], target: number): number {
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: Identify the initialization error
High should be the last valid index, which isarr.length - 1, notarr.length.Step 2: Understand impact of wrong high value
Setting high to arr.length causes out-of-bound access at arr[mid] when mid equals arr.length.Final Answer:
Changelet high = arr.length;tolet high = arr.length - 1;-> Option AQuick Check:
High index must be last valid array index [OK]
- Setting high to array length causing out-of-bounds
- Changing loop condition incorrectly
- Using ceil instead of floor for mid
Solution
Step 1: Understand the problem with duplicates
Standard binary search returns any occurrence, not necessarily the first.Step 2: Modify search to find first occurrence
When target found at mid, move high to mid - 1 to continue searching left side for earlier occurrence.Step 3: Keep track of potential answer
Store mid as potential answer and continue until low > high.Final Answer:
When arr[mid] equals target, update high to mid - 1 and continue searching left -> Option CQuick Check:
Move left on match to find first occurrence [OK]
- Returning immediately on first match
- Searching right side on match
- Ignoring duplicates in binary search
Ready to prove it?
Pass the test and this pattern moves unknown
