DSA AnimatorREVISION VIDEOS
← Back to problems
New

Search in Rotated Sorted Array — LeetCode 33 video explanation

A sorted array of distinct numbers was rotated at an unknown point. Return the index of the target, or minus 1, in O of log n time.

Loading videos…

DSA Animator › DSA Revision › Binary Search › Search in Rotated Sorted Array

Key moments in the Search in Rotated Sorted Array video

0:04Problem0:13Example0:19Brute force0:25Key idea0:39Dry run0:57Code1:13Takeaway

What you will learn

Remember: one half of a rotated array is always sorted. Check if the target fits in the sorted half, and discard the other one. The video solves Search in Rotated Sorted Array (LeetCode 33, Medium) with the Binary Search pattern from the Binary Search topic, and you can replay every step in the interactive Search in Rotated Sorted Array animation.

Search in Rotated Sorted Array video transcript

Problem

A sorted array of distinct numbers was rotated at an unknown point. Return the index of the target, or minus 1, in O of log n time.

Example

For 4, 5, 6, 7, 0, 1, 2 and target 0, the answer is index 4.

Brute force

A linear scan is O of n. Normal binary search fails, because the whole array is not sorted.

Key idea

Cut at mid, and at least one of the two halves is still sorted. Check if the left half is sorted by comparing the value at low with the value at mid. If the target lies inside the sorted half, search there. Otherwise, search the other half.

Dry run

Low 0, high 6, mid 3 holds 7. The left half 4 to 7 is sorted, but 0 is not inside it, so low becomes 4. Mid 5 holds 1, and the left part 0 to 1 is sorted and contains 0, so high becomes 4. Mid 4 holds 0, which is the target, so the answer is 4.

Code

In code, return mid on a match. If the value at low is at most the value at mid, the left half is sorted, so check if the target is inside it. Otherwise the right half is sorted, so check that range instead. Each step drops half, so it's O of log n time.

Takeaway

Remember: one half of a rotated array is always sorted. Check if the target fits in the sorted half, and discard the other one.

More Binary Search revision videos

← All 185 DSA revision videos