Welcome to Day 26 of the Tekraze DSA series. The binary search chapter keeps growing. We searched a plain sorted array, a sorted grid and then the range of possible answers in Koko Eating Bananas. Today the array is still sorted, but someone has rotated it. Find Minimum in Rotated Sorted Array teaches you to use binary search even when the order looks broken, and it is one of the most asked warm up questions in interviews.
What is the Find Minimum in Rotated Sorted Array problem?
You get an array nums of unique integers that was sorted in ascending order and then rotated some number of times. Rotating once moves the last element to the front, so [0, 1, 2, 4, 5, 6, 7] rotated four times becomes [4, 5, 6, 7, 0, 1, 2]. Return the smallest element. The catch is that your solution must run in O(log n) time.
Input: nums = [3, 4, 5, 1, 2]
Output: 1
Input: nums = [4, 5, 6, 7, 0, 1, 2]
Output: 0
Input: nums = [11, 13, 15, 17]
Output: 11
How should you think about it in plain words?
Picture the rotated array as two sorted staircases placed side by side. The first staircase holds the big values and the second one holds the small values. The minimum is the very first step of the second staircase, the spot where the numbers suddenly drop. Every value in the left staircase is bigger than every value in the right one.
So look at any middle element and compare it with the last element. If the middle is bigger than the last, the middle is still on the left staircase and the drop is somewhere to its right. If the middle is smaller than or equal to the last, the middle sits on the right staircase, so the drop is at the middle or before it. One comparison throws away half the array, which is exactly what binary search needs.
What does the brute force approach look like?
Just scan every element and keep the smallest one.
def find_min_brute(nums):
smallest = nums[0]
for x in nums:
smallest = min(smallest, x)
return smallest
This takes O(n) time and O(1) space. It is correct, but it ignores the fact that the array is almost sorted, and the problem asks for O(log n), so an interviewer will expect more.
How do we get the optimal solution?
Set left = 0 and right = n – 1. While left < right, take mid. If nums[mid] > nums[right], the drop is to the right of mid, so move left = mid + 1. Otherwise mid might be the minimum itself, so keep it with right = mid. When the two pointers meet, they point at the smallest value.
Walking through [4, 5, 6, 7, 0, 1, 2], we start with left 0 and right 6. Mid is 3 with value 7, which is bigger than 2, so left becomes 4. Now mid is 5 with value 1, which is not bigger than 2, so right becomes 5. Mid is 4 with value 0, which is not bigger than 1, so right becomes 4. Left and right meet at index 4 and the answer is 0.
Time is O(log n) because every step halves the search range. Space is O(1) since we only keep two pointers. If you want a refresher on why halving is so fast compared with a full scan, read our Big O helper post on time and space complexity.
Java solution
public class Solution {
// Binary search for the smallest value in a rotated sorted array
public static int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) {
left = mid + 1; // minimum is to the right of mid
} else {
right = mid; // mid could be the minimum
}
}
return nums[left];
}
public static void main(String[] args) {
int[][] tests = {{3, 4, 5, 1, 2}, {4, 5, 6, 7, 0, 1, 2}, {11, 13, 15, 17}, {1}, {2, 1}};
int[] expected = {1, 0, 11, 1, 1};
boolean ok = true;
for (int i = 0; i < tests.length; i++) {
int got = findMin(tests[i]);
System.out.println("Test " + (i + 1) + ": " + got + (got == expected[i] ? " PASS" : " FAIL"));
ok &= got == expected[i];
}
System.out.println(ok ? "ALL PASSED" : "SOME FAILED");
}
}
Using left + (right – left) / 2 keeps the middle index safe from int overflow on very large arrays.
Python solution
def find_min(nums):
"""Binary search for the smallest value in a rotated sorted array."""
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1 # minimum is to the right of mid
else:
right = mid # mid could be the minimum
return nums[left]
if __name__ == "__main__":
tests = [([3, 4, 5, 1, 2], 1), ([4, 5, 6, 7, 0, 1, 2], 0),
([11, 13, 15, 17], 11), ([1], 1), ([2, 1], 1)]
ok = True
for i, (nums, want) in enumerate(tests, 1):
got = find_min(nums)
print(f"Test {i}: {got} {'PASS' if got == want else 'FAIL'}")
ok &= got == want
print("ALL PASSED" if ok else "SOME FAILED")
Rust solution
The Rust version uses usize indexes. Because we never write right = mid – 1, the index can never go below zero and panic.
// Binary search for the smallest value in a rotated sorted array
fn find_min(nums: &[i32]) -> i32 {
let (mut left, mut right) = (0usize, nums.len() - 1);
while left < right {
let mid = left + (right - left) / 2;
if nums[mid] > nums[right] {
left = mid + 1; // minimum is to the right of mid
} else {
right = mid; // mid could be the minimum
}
}
nums[left]
}
fn main() {
let tests: Vec<(Vec<i32>, i32)> = vec![
(vec![3, 4, 5, 1, 2], 1),
(vec![4, 5, 6, 7, 0, 1, 2], 0),
(vec![11, 13, 15, 17], 11),
(vec![1], 1),
(vec![2, 1], 1),
];
let mut ok = true;
for (i, (nums, want)) in tests.iter().enumerate() {
let got = find_min(nums);
println!("Test {}: {} {}", i + 1, got, if got == *want { "PASS" } else { "FAIL" });
ok &= got == *want;
}
println!("{}", if ok { "ALL PASSED" } else { "SOME FAILED" });
}
All three programs ran the five sample cases, [3,4,5,1,2], [4,5,6,7,0,1,2], [11,13,15,17], [1] and [2,1], and every check passed in Java, Python and Rust.
What are the tips and tricks for an easy solution?
Spot the pattern. Sorted plus rotated plus a demand for O(log n) almost always means binary search with a twist.
Compare with the right end. Comparing nums[mid] with nums[right] always tells you which side the drop is on. Comparing with the left end gets confusing when the array is not rotated at all.
Quick shortcut. If nums[left] < nums[right], that slice is already sorted and nums[left] is the minimum, so you can return early.
Use the left less than right loop. With right = mid the loop ends with both pointers on the answer, so there is no extra check after it.
Edge cases. A single element, two elements like [2, 1], an array that is not rotated, and one rotated by n minus one positions.
Interview tip. Explain the two staircases picture first. Once the interviewer sees why one comparison removes half the array, the code takes a minute.
What are the common mistakes people make?
- Writing right = mid – 1 when nums[mid] <= nums[right], which can skip the minimum when mid is the answer.
- Using while (left <= right) together with right = mid, which can loop forever.
- Comparing mid with nums[left] and forgetting the case where the array is not rotated.
- Computing mid as (left + right) / 2 in Java on huge arrays, which can overflow.
- Applying this exact code to arrays with duplicates. When equal values are allowed you need an extra right -= 1 step and the worst case becomes O(n).
Where is this pattern used in the real world?
Rotated sorted data shows up more often than you might think. Circular log buffers and ring buffers keep entries in time order but wrap around, so finding the oldest entry is exactly this problem.
Rotated log files and time series stored in a fixed size circular store need the same trick to find where the newest data starts. Consistent hashing rings in distributed caches and databases look up the first node clockwise from a hash, which is a binary search on a sorted ring. Version control tools like git bisect also rely on spotting the single point where a sequence flips from good to bad.
Which earlier posts in the series should you read?
Start with Day 1, Two Sum for hash map basics and Day 2, Best Time to Buy and Sell Stock for tracking a running minimum.
Day 3, Contains Duplicate, Day 4, Valid Anagram and Day 5, Group Anagrams build the counting toolkit, Day 6, Valid Palindrome, Day 7, Two Sum II, Day 8, 3Sum and Day 9, Container With Most Water cover two pointers, and Day 10, Longest Substring Without Repeating Characters, Day 11, Longest Repeating Character Replacement and Day 12, Minimum Window Substring walk through the sliding window section.
Day 13, Valid Parentheses, Day 14, Min Stack, Day 15, Evaluate Reverse Polish Notation and Day 16, Daily Temperatures cover the stack chapter, Day 17, Implement Queue using Stacks shows how two stacks make a queue, and Day 18, Reverse Linked List, Day 19, Merge Two Sorted Lists and Day 20, Linked List Cycle cover the linked list chapter.
Keep our data structures cheat sheet handy for a quick refresher on arrays and searching.
Frequently asked questions
What is the Find Minimum in Rotated Sorted Array problem?
You get a sorted array of unique numbers that has been rotated some number of times, and you must return its smallest element in O(log n) time.
Why compare the middle element with the rightmost element?
If the middle value is bigger than the rightmost value, the drop point and the minimum lie to the right of the middle. Otherwise the minimum is at the middle or to its left. This one comparison always removes half of the array.
What is the time complexity of Find Minimum in Rotated Sorted Array?
The binary search solution runs in O(log n) time and uses O(1) extra space. The simple linear scan takes O(n) time.
What changes if the rotated array has duplicates?
When nums[mid] equals nums[right] you cannot tell which side holds the minimum, so you shrink the range with right minus one. It still works, but the worst case becomes O(n).
Which problems are similar to Find Minimum in Rotated Sorted Array?
Search in Rotated Sorted Array, Find Minimum in Rotated Sorted Array II with duplicates, Find Peak Element and Search in Rotated Sorted Array II all use the same modified binary search idea.





