Algo-Sim › Binary Search

Search in Rotated Sorted Array

Medium · Binary Search · step through it in Java, Python and C++ on your own input

Find target in a sorted array of distinct values that was rotated at an unknown pivot, in O(log n).

Problem

An array of distinct integers was sorted in increasing order and then rotated: some prefix was moved to the end, as in [4, 5, 6, 7, 0, 1, 2]. Given this array and a target, return the index of target, or -1 if it is absent, in O(log n) time.

Constraints

Edge cases to test

Follow-up questions

What if values can repeat?
When nums[lo] == nums[mid] == nums[hi], shrink both ends by one; the worst case becomes O(n) (LC 81).
Is there a two-phase approach?
Find the rotation point (the minimum) first, then binary search the correct half: two O(log n) searches.

Solution

Java

public 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]) {
            if (nums[lo] <= target && target < nums[mid]) hi = mid - 1;
            else lo = mid + 1;
        } else {
            if (nums[mid] < target && target <= nums[hi]) lo = mid + 1;
            else hi = mid - 1;
        }
    }
    return -1;
}

Python

def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if nums[mid] == target: return mid
        if nums[lo] <= nums[mid]:
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int search(vector<int> &nums, int target) {
        int lo = 0, hi = int(nums.size()) - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] == target)
                return mid;
            if (nums[lo] <= nums[mid]) {
                if (nums[lo] <= target && target < nums[mid])
                    hi = mid - 1;
                else
                    lo = mid + 1;
            } else {
                if (nums[mid] < target && target <= nums[hi])
                    lo = mid + 1;
                else
                    hi = mid - 1;
            }
        }
        return -1;
    }
};

More Binary Search problems