Find Peak Element Using Binary Search in DSA Rust - Time & Space Complexity
We want to understand how fast the binary search method finds a peak element in an array.
How does the number of steps grow as the array gets bigger?
Analyze the time complexity of the following code snippet.
fn find_peak(nums: &[i32]) -> usize {
let mut left = 0;
let mut right = nums.len() - 1;
while left < right {
let mid = left + (right - left) / 2;
if nums[mid] > nums[mid + 1] {
right = mid;
} else {
left = mid + 1;
}
}
left
}
This code finds a peak element index by repeatedly narrowing the search range using 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 one element, about log base 2 of n times.
Each step cuts the search area roughly in half, so the number of steps grows slowly as the array 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 extra step.
Time Complexity: O(log n)
This means the steps needed grow very slowly even if the array gets much bigger.
[X] Wrong: "The loop runs n times because it looks at each element."
[OK] Correct: The loop does not check every element; it jumps by halves, so it runs much fewer times than n.
Knowing how binary search reduces steps quickly shows your understanding of efficient searching, a key skill in many coding challenges.
"What if we changed the array to be unsorted without the peak property? How would the time complexity change?"
Practice
Solution
Step 1: Understand the definition of a peak element
A peak element is one that is strictly greater than its neighbors on both sides (or just one side if at an edge).Step 2: Apply this to binary search context
Binary search finds such an element by comparing mid element with neighbors to decide search direction.Final Answer:
An element greater than its neighbors -> Option DQuick Check:
Peak element = element greater than neighbors [OK]
- Confusing peak with smallest element
- Thinking peak must be at array start
- Assuming peak equals neighbors
nums?Solution
Step 1: Identify correct boundary initialization
Binary search on array indices starts at 0 and ends at length - 1 because indexing is zero-based.Step 2: Check mutability and correct tuple assignment
We need mutable variables for left and right to update during search, so usemutand assign (0, nums.len() - 1).Final Answer:
let (mut left, mut right) = (0, nums.len() - 1); -> Option AQuick Check:
Start=0, End=length-1, mutable [OK]
- Using length instead of length - 1 as right boundary
- Not declaring variables as mutable
- Starting from 1 instead of 0
nums = vec![1, 3, 2, 1] using binary search peak finding?Solution
Step 1: Analyze the array and identify peak candidates
Array is [1, 3, 2, 1]. Element at index 1 is 3, which is greater than neighbors 1 and 2.Step 2: Confirm binary search would find index 1
Binary search compares mid with neighbors and moves left or right. Mid initially at index 1 or 2 will find 3 as peak.Final Answer:
1 -> Option BQuick Check:
Peak element 3 at index 1 [OK]
- Choosing first or last index incorrectly
- Confusing peak with any max element
- Ignoring neighbors comparison
let mut left = 0;
let mut right = nums.len();
while left < right {
let mid = (left + right) / 2;
if nums[mid] < nums[mid + 1] {
left = mid + 1;
} else {
right = mid;
}
}
return left;Solution
Step 1: Check boundary initialization
Right boundary is set to nums.len(), which is out of valid index range (max index is len - 1).Step 2: Understand impact on mid + 1 access
Accessing nums[mid + 1] can cause out-of-bounds panic if mid is at last index due to wrong right boundary.Final Answer:
Right boundary should be nums.len() - 1 -> Option AQuick Check:
Right = len - 1 to avoid out-of-bounds [OK]
- Setting right to length instead of length - 1
- Ignoring out-of-bounds access on mid + 1
- Changing loop condition incorrectly
nums = vec![1, 2, 3, 1, 5, 6, 4], which index will the binary search peak finding algorithm return and why?Solution
Step 1: Identify all peak elements in the array
Array: [1, 2, 3, 1, 5, 6, 4]. Peaks are elements greater than neighbors: 3 at index 2 and 6 at index 5.Step 2: Trace binary search behavior
left=0, right=6; mid=3 (1 < 5), left=4; mid=5 (6 > 4), right=5; mid=4 (5 < 6), left=5. Returns index 5.Final Answer:
5, because 6 is a peak after the drop -> Option CQuick Check:
Binary search finds peak at index 5 [OK]
- Assuming it always finds the first peak
- Choosing middle element without checking neighbors
- Ignoring multiple peaks in array
Ready to prove it?
Pass the test and this pattern moves unknown
