Search in Rotated Sorted Array in DSA Javascript - Time & Space Complexity
We want to know how fast we can find a number in a rotated sorted list. This helps us understand the cost of searching when the list is not fully sorted.
The question is: How does the search time grow as the list gets bigger?
Analyze the time complexity of the following code snippet.
function searchRotatedArray(nums, target) {
let left = 0, right = nums.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] === target) return mid;
if (nums[left] <= nums[mid]) {
if (nums[left] <= target && target < nums[mid]) right = mid - 1;
else left = mid + 1;
} else {
if (nums[mid] < target && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}
return -1;
}
This code searches for a target number in a rotated sorted array using a modified binary search.
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 size each time.
Each step cuts the list roughly in half, so the number of steps grows slowly as the list grows.
| 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 more step, showing slow growth.
Time Complexity: O(log n)
This means the search time grows very slowly even if the list gets much bigger, because we cut the search area in half each step.
[X] Wrong: "Because the array is rotated, we must check every element, so it takes linear time O(n)."
[OK] Correct: The code cleverly uses the sorted parts to decide which half to search next, so it still works in logarithmic time.
Understanding this search method shows you can adapt classic techniques to tricky situations, a skill valued in problem solving and interviews.
"What if the array was not rotated but had duplicates? How would the time complexity change?"
Practice
Solution
Step 1: Understand the array structure
A rotated sorted array is created by taking a sorted array and rotating it at some pivot, splitting it into two sorted parts.Step 2: Reason about search difficulty
Normal binary search assumes the whole array is sorted, but here the array is split, so we must adjust the search to handle two sorted parts.Final Answer:
The array is split into two sorted parts, so normal binary search needs adjustment -> Option DQuick Check:
Rotated array = split sorted parts [OK]
- Assuming the entire array is sorted
- Ignoring the pivot point
- Using linear search instead of binary search
Solution
Step 1: Identify valid index range for binary search
Binary search uses zero-based indexing, so left starts at 0 and right at last index (length - 1).Step 2: Check each option
let left = 0, right = arr.length - 1; correctly sets left=0 and right=arr.length-1. Others have invalid ranges or off-by-one errors.Final Answer:
let left = 0, right = arr.length - 1; -> Option AQuick Check:
Index range = 0 to length-1 [OK]
- Using right = arr.length (out of bounds)
- Starting left at 1 instead of 0
- Negative indices for left or right
const arr = [4,5,6,7,0,1,2];
function search(nums, target) {
let left = 0, right = nums.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] === target) return mid;
if (nums[left] <= nums[mid]) {
if (target >= nums[left] && target < nums[mid]) right = mid - 1;
else left = mid + 1;
} else {
if (target > nums[mid] && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}
return -1;
}
console.log(search(arr, 0));Solution
Step 1: Understand the array and target
The array is rotated sorted: [4,5,6,7,0,1,2], target is 0.Step 2: Trace the binary search steps
Initial left=0, right=6, mid=3 (value 7). Left half is sorted (4 to 7). Target 0 is not in left half, so search right half: left=4, right=6.
New mid=5 (value 1). Left half (0 to 1) is sorted. Target 0 is in left half, so right=4.
New mid=4 (value 0), found target at index 4.Final Answer:
4 -> Option CQuick Check:
Target 0 found at index 4 [OK]
- Not updating left/right correctly
- Confusing sorted half
- Returning wrong index or -1
function search(nums, target) {
let left = 0, right = nums.length - 1;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] === target) return mid;
if (nums[left] <= nums[mid]) {
if (target >= nums[left] && target < nums[mid]) right = mid - 1;
else left = mid + 1;
} else {
if (target > nums[mid] && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}
return -1;
}Solution
Step 1: Analyze the loop condition
The loop uses while(left < right), which misses checking when left equals right, possibly skipping the last element.Step 2: Correct the loop condition
Changing to while(left <= right) ensures all elements are checked, including when left == right.Final Answer:
The loop condition should be left <= right, not left < right -> Option AQuick Check:
Loop must cover all indices [OK]
- Using while(left < right) misses last element
- Incorrect mid calculation (not here though)
- Returning wrong index when not found
const arr = [2,5,6,0,0,1,2];
function search(nums, target) {
let left = 0, right = nums.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] === target) return true;
if (nums[left] === nums[mid] && nums[mid] === nums[right]) {
left++;
right--;
} else if (nums[left] <= nums[mid]) {
if (target >= nums[left] && target < nums[mid]) right = mid - 1;
else left = mid + 1;
} else {
if (target > nums[mid] && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}
return false;
}Solution
Step 1: Understand duplicates impact
Duplicates can cause ambiguity in deciding which half is sorted, breaking normal binary search logic.Step 2: Skip duplicates when left, mid, right are equal
When nums[left] == nums[mid] == nums[right], increment left and decrement right to skip duplicates and reduce search space.Final Answer:
Add checks to skip duplicates when left, mid, right are equal -> Option BQuick Check:
Skip duplicates to maintain binary search correctness [OK]
- Ignoring duplicates causing infinite loops
- Trying to remove duplicates before search
- Switching to linear search unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
