Skip to lesson

Rotated arrays and peaks

A sorted array [0, 1, 2, 4, 5, 6, 7] rotated at pivot index 3 becomes [4, 5, 6, 7, 0, 1, 2]. It is no longer globally sorted, yet you can still search it—and even find a local peak in an arbitrary array—in O(log n) time! The secret is realizing that binary search only needs a testable property that eliminates half the range at each step.

Search in a rotated sorted array

When you pick any midpoint mid in a rotated sorted array of distinct elements (such as nums = [4, 5, 6, 7, 0, 1, 2]), the single drop (the rotation cliff between 7 and 0) can sit in at most one of the two halves.

  1. If nums[mid] == target, return mid.
  2. Check if the left half [lo .. mid] is sorted (nums[lo] <= nums[mid]): if nums[lo] <= target && target < nums[mid], search left (hi = mid - 1); otherwise search right (lo = mid + 1).
  3. Otherwise the right half [mid .. hi] is guaranteed sorted: if nums[mid] < target && target <= nums[hi], search right (lo = mid + 1); otherwise search left (hi = mid - 1).

Example 1 · Search in a rotated sorted array

SearchRotatedArrayDemo.javaJava
public class SearchRotatedArrayDemo {    public static int search(int[] nums, int target) {        int lo = 0, hi = nums.length - 1;        while (lo <= hi) {            int mid = lo + (hi - lo) / 2;            if (nums[mid] == target) return mid;
            if (nums[lo] <= nums[mid]) { // Left half [lo..mid] is sorted                if (nums[lo] <= target && target < nums[mid]) {                    hi = mid - 1;                } else {                    lo = mid + 1;                }            } else { // Right half [mid..hi] is sorted                if (nums[mid] < target && target <= nums[hi]) {                    lo = mid + 1;                } else {                    hi = mid - 1;                }            }        }        return -1;    }
    public static void main(String[] args) {        int[] nums = {4, 5, 6, 7, 0, 1, 2};        System.out.println("Index of 0: " + search(nums, 0));        System.out.println("Index of 5: " + search(nums, 5));        System.out.println("Index of 3: " + search(nums, 3));    }}
Output
Index of 0: 4
Index of 5: 1
Index of 3: -1

What this code does

  • At each step, we test nums[lo] <= nums[mid] to see which half is contiguous and sorted.
  • Then a simple range check on that sorted half's endpoints tells us whether target is inside it or in the other half.

Therefore, at least one half—either [lo .. mid] or [mid .. hi]—is guaranteed to be normally sorted! Once you identify which half is sorted by comparing nums[lo] <= nums[mid], you can immediately test whether target falls inside that sorted half's endpoints (nums[lo] <= target && target < nums[mid]):

Notice the <= in nums[lo] <= nums[mid]: when lo == mid (a 2-element subarray), the 1-element left subarray [lo .. mid] is trivially sorted!

Minimum of a rotated array

How do you find the minimum element (which is also the rotation count!) in nums = [4, 5, 6, 7, 0, 1, 2] in O(log n) time?

Example 2 · Finding the minimum (and rotation pivot) in a rotated sorted array

FindMinRotatedDemo.javaJava
public class FindMinRotatedDemo {    public static int findMinIndex(int[] nums) {        int lo = 0, hi = nums.length - 1;        while (lo < hi) {            int mid = lo + (hi - lo) / 2;            if (nums[mid] > nums[hi]) {                lo = mid + 1;            } else {                hi = mid;            }        }        return lo;    }
    public static void main(String[] args) {        int[] a1 = {4, 5, 6, 7, 0, 1, 2};        int[] a2 = {11, 13, 15, 17};        int idx1 = findMinIndex(a1);        int idx2 = findMinIndex(a2);        System.out.println("a1 min=" + a1[idx1] + " at index " + idx1);        System.out.println("a2 min=" + a2[idx2] + " at index " + idx2);    }}
Output
a1 min=0 at index 4
a2 min=11 at index 0

What this code does

  • Comparing nums[mid] against nums[hi] works even when the array is not rotated at all (like a2).
  • In a2, nums[mid] < nums[hi] is always true, so hi walks down to 0.
  • If nums[mid] > nums[hi]: mid is on the upper plateau, so the minimum must lie strictly to the right (lo = mid + 1).
  • If nums[mid] < nums[hi]: mid is on the lower plateau (and could itself be the minimum!), so keep mid in range (hi = mid).
  • When lo == hi, lo is the index of the minimum element (and the number of times the sorted array was rotated right).

Compare nums[mid] with the right endpoint nums[hi] using while (lo < hi):

  • Every element in the rotated left chunk (4, 5, 6, 7) is strictly greater than nums[hi] (2).
  • Every element in the right chunk (0, 1, 2) is less than or equal to nums[hi] (2). So comparing nums[mid] with nums[hi] tells you which side of the cliff mid sits on:

Finding a peak element

A peak element is an element that is strictly greater than its immediate neighbors (nums[i] > nums[i - 1] and nums[i] > nums[i + 1], treating out-of-bounds ends nums[-1] and nums[n] as -∞).

Example 3 · Finding a peak element by following the rising slope

FindPeakElementDemo.javaJava
public class FindPeakElementDemo {    public static int findPeakElement(int[] nums) {        int lo = 0, hi = nums.length - 1;        while (lo < hi) {            int mid = lo + (hi - lo) / 2;            if (nums[mid] < nums[mid + 1]) {                lo = mid + 1; // rising slope to the right            } else {                hi = mid;     // falling slope, peak at or left of mid            }        }        return lo;    }
    public static void main(String[] args) {        int[] nums = {1, 2, 1, 3, 5, 6, 4};        int peakIdx = findPeakElement(nums);        System.out.println("Peak index: " + peakIdx + ", value: " + nums[peakIdx]);    }}
Output
Peak index: 5, value: 6

What this code does

  • Because lo < hi inside the loop, mid is strictly less than hi, so nums[mid + 1] is always a valid index.
  • Climbing in the direction of the larger neighbor guarantees we converge on a local peak in O(log n) steps.

Even in an unsorted array where adjacent elements differ (nums[i] != nums[i + 1]), you can find a peak in O(log n) time! Why? Compare nums[mid] with its right neighbor nums[mid + 1]:

  • If nums[mid] < nums[mid + 1], you are on a rising slope going right. Since the right boundary nums[n] = -∞ eventually drops, the slope must crest at least once in [mid + 1 .. hi], so set lo = mid + 1.
  • If nums[mid] > nums[mid + 1], you are on a falling slope going right (or already at a peak). Since the left boundary nums[-1] = -∞ starts low, a peak is guaranteed to exist in [lo .. mid], so set hi = mid.

Next step

Check your understanding

10 quick questions