Binary Search as Divide and Conquer in DSA Typescript - Time & Space Complexity
We want to understand how fast binary search finds a number in a sorted list.
How does the time it takes change as the list gets bigger?
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 looks for a target number in a sorted list by repeatedly cutting the search area in half.
Identify the loops, recursion, array traversals that repeat.
- 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 checks |
| 100 | About 7 checks |
| 1000 | About 10 checks |
Pattern observation: Doubling the list size adds only one more check.
Time Complexity: O(log n)
This means the time to find the target grows slowly, adding just a few more steps even if the list gets much bigger.
[X] Wrong: "Binary search checks every element one by one like a simple search."
[OK] Correct: Binary search skips half the list each time, so it does far fewer checks than looking at every element.
Understanding binary search time helps you explain how to quickly find items in sorted data, a key skill in many coding tasks.
"What if the list was not sorted? How would the time complexity of searching change?"
Practice
Binary Search as a divide and conquer algorithm?Solution
Step 1: Understand binary search principle
Binary search works by dividing the sorted list into two halves and deciding which half to continue searching in.Step 2: Compare target with middle element
By comparing the target with the middle element, we eliminate half the list each time, making search efficient.Final Answer:
Repeatedly split the sorted list into halves to find the target -> Option DQuick Check:
Divide and conquer = split list halves [OK]
- Thinking binary search works on unsorted lists
- Searching linearly instead of dividing
- Ignoring the middle element comparison
Solution
Step 1: Identify input and output types
Binary search takes an array of numbers and a target number, returning the index (number) or -1 if not found.Step 2: Match function signature
function binarySearch(arr: number[], target: number): number matches input types (number array and number) and returns a number index, which is correct.Final Answer:
function binarySearch(arr: number[], target: number): number -> Option AQuick Check:
Input: number[], number; Output: number [OK]
- Swapping array and target types
- Returning void instead of index
- Using wrong array element types
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;
}
const nums = [2, 4, 6, 8, 10];
console.log(binarySearch(nums, 6));Solution
Step 1: Identify array and target
Array is [2,4,6,8,10], target is 6.Step 2: Trace binary search steps
Middle index initially is 2 (value 6), which matches target, so function returns 2 immediately.Final Answer:
2 -> Option AQuick Check:
Index of 6 in array = 2 [OK]
- Confusing index with value
- Off-by-one errors in mid calculation
- Returning wrong index when target found
function binarySearch(arr: number[], target: number): number {
let left = 0;
let right = arr.length;
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;
}Solution
Step 1: Check right boundary initialization
Right should be last valid index, which is arr.length - 1, not arr.length (out of bounds).Step 2: Understand impact on loop
Using arr.length causes mid to sometimes be out of array range, causing runtime errors.Final Answer:
Change right initialization to arr.length - 1 -> Option CQuick Check:
Right boundary = last index [OK]
- Setting right to arr.length causes out-of-bounds
- Changing loop condition incorrectly
- Miscalculating mid index
[1, 2, 2, 2, 3, 4]. How would you modify binary search to find the first occurrence of 2?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
After finding target, continue searching left half to check if earlier occurrence exists, updating result accordingly.Final Answer:
After finding 2, continue searching left half to find earlier occurrence -> Option BQuick Check:
Find first occurrence by searching left side [OK]
- Stopping at first found index
- Searching right half after match
- Switching to linear search unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
