What if you could find anything in a huge list in just a few quick steps?
Why Binary Search Iterative Approach in DSA Typescript?
Imagine you have a huge phone book with thousands of names sorted alphabetically. You want to find the phone number for a friend. If you start from the first page and look at every name one by one, it will take a very long time.
Searching one by one is slow and tiring. It wastes time because you check many names unnecessarily. Also, it is easy to lose your place or make mistakes when flipping through so many pages.
Binary search helps by quickly cutting the search area in half each time. Instead of checking every name, you jump to the middle, decide if your friend's name is before or after, and then only search that half. This way, you find the name much faster and with fewer mistakes.
function findName(names: string[], target: string): number {
for (let index = 0; index < names.length; index++) {
if (names[index] === target) {
return index;
}
}
return -1;
}function binarySearch(names: string[], target: string): number {
let left = 0;
let right = names.length - 1;
while (left <= right) {
const middle = Math.floor((left + right) / 2);
if (names[middle] === target) return middle;
else if (names[middle] < target) left = middle + 1;
else right = middle - 1;
}
return -1;
}Binary search enables lightning-fast searching in sorted lists, making large data easy to handle.
When you search for a word in a dictionary app, binary search helps find the word instantly instead of scanning every page.
Manual search checks every item, which is slow for big lists.
Binary search cuts the search space in half repeatedly for speed.
It works only on sorted lists but makes searching very efficient.
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
