Binary Search Recursive Approach in DSA Javascript - Time & Space Complexity
We want to understand how the time taken by recursive binary search changes as the input 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, target, left = 0, right = arr.length - 1) {
if (left > right) return -1;
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] > target) return binarySearch(arr, target, left, mid - 1);
else return binarySearch(arr, target, mid + 1, right);
}
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: Recursive call that halves the search range each time.
- How many times: At most, the function calls itself until the search range is empty, roughly halving the size each time.
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 number of steps grows slowly, increasing by one each time the input size doubles.
[X] Wrong: "Binary search checks every element one by one, so it is O(n)."
[OK] Correct: Binary search does not check every element; it cuts the search area in half each time, so it needs far fewer steps.
Understanding binary search time complexity shows you can analyze efficient algorithms that use divide and conquer, a key skill in many coding challenges.
"What if the array was not sorted? How would the time complexity of this search change?"
Practice
binary search recursive approach when searching for a value in a sorted array?Solution
Step 1: Understand binary search logic
Binary search works by dividing the sorted array into two halves and deciding which half to search next based on comparison.Step 2: Recognize recursive approach
In recursion, the function calls itself on the half where the target value may exist, reducing the search space each time.Final Answer:
Divide the array into halves and search recursively in the half where the value can be. -> Option AQuick Check:
Binary search = divide and conquer [OK]
- Thinking binary search checks every element linearly
- Confusing recursion with iteration
- Not requiring the array to be sorted
Solution
Step 1: Identify base case meaning
The base case stops recursion when the search space is empty, which happens if start index passes end index.Step 2: Match base case condition
The conditionstart > endmeans no elements left to search, so return -1 to indicate not found.Final Answer:
if (start > end) return -1; -> Option BQuick Check:
Base case = empty search space [OK]
- Using incorrect comparison like start == end as base case
- Returning wrong index or value in base case
- Confusing base case with recursive step
function binarySearch(arr, target, start, end) {
if (start > end) return -1;
const mid = Math.floor((start + end) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] > target) return binarySearch(arr, target, start, mid - 1);
else return binarySearch(arr, target, mid + 1, end);
}
const array = [2, 4, 6, 8, 10];
console.log(binarySearch(array, 6, 0, array.length - 1));Solution
Step 1: Trace initial call
Start=0, end=4, mid=2 (element 6). Since arr[mid] == target (6), return mid = 2.Step 2: Confirm output
The function returns 2 immediately without further recursion.Final Answer:
2 -> Option AQuick Check:
Target found at index 2 [OK]
- Miscomputing mid index
- Confusing index with value
- Forgetting zero-based indexing
function binarySearch(arr, target, start, end) {
if (start >= end) return -1;
const mid = Math.floor((start + end) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] > target) return binarySearch(arr, target, start, mid - 1);
else return binarySearch(arr, target, mid + 1, end);
}Solution
Step 1: Analyze base case condition
The base case incorrectly usesstart >= end, which misses the case when start == end and the element could still be at that index.Step 2: Correct base case
Changing it tostart > endensures the search includes the last element before stopping.Final Answer:
Change base case to if (start > end) return -1; -> Option DQuick Check:
Base case must allow start == end check [OK]
- Stopping search too early by wrong base case
- Changing mid calculation unnecessarily
- Returning wrong index on success
Solution
Step 1: Understand duplicates in binary search
Standard binary search returns any occurrence, but to find first occurrence, we must check if earlier duplicates exist.Step 2: Modify recursion on match
When arr[mid] == target, recursively search left half to find if an earlier occurrence exists; if none, mid is first occurrence.Final Answer:
When arr[mid] == target, continue searching left half to find earlier occurrence. -> Option CQuick Check:
Find first occurrence by searching left on match [OK]
- Returning first found index without checking left side
- Searching right half on match incorrectly
- Using linear search unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
