Minimum in a Rotated Sorted Array

medium Searching and Sorting

Problem

A sorted array of different numbers was rotated (the last part moved to the front, for example 1 3 5 7 9 became 7 9 1 3 5). Print the smallest number. Use binary search: O(log n).

Constraints

  • 1 <= n <= 10^5
  • all numbers are different

Examples

Input

5
7 9 1 3 5

Output

1

Solutions

Best approachTime O(log n)Space O(1)

The rotation point is where the numbers drop. The middle compared with the last number shows on which side of that point we are. Each step halves the range.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Minimum of a rotated array.
 * Input   : n, then n integers.
 * Output  : The smallest.
 * Approach: Binary search.
 * Time    : O(log n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: Compare the middle with the last number. If middle is bigger, the smallest number is to the right of middle.
        int low = 0;
        int high = a.length - 1;
        while (low < high) {
            int middle = low + (high - low) / 2;
            if (a[middle] > a[high]) {
                low = middle + 1;
            } else {
                // Step 2: Otherwise the right half is sorted, so the smallest number is middle or to its left.
                high = middle;
            }
        }
        return a[low];
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (2)
  1. What does a[middle] > a[high] mean?
  2. Why do we compare with a[high] and not a[low]?