Binary search and sorting · Problem 2 of 3

Search a rotated sorted list

Pattern: Search in a Rotated Sorted Array

mediumNot solved yet

The problem

A bus schedule lists departure times as distinct numbers in increasing order, but the list was rotated: it starts somewhere in the middle and wraps around, like [40, 50, 60, 10, 20, 30]. Write a function that returns the index of target, or -1 if it isn't there, in O(log n) time.

The list might not be rotated at all, and it might be empty.

text
1find_in_rotated([40, 50, 60, 10, 20, 30], 20)  ->  4
2find_in_rotated([40, 50, 60, 10, 20, 30], 45)  ->  -1
3find_in_rotated([10, 20, 30], 10)              ->  0
Example 1: finding 201 / 2
lowmidhigh
40
0
50
1
60
2
10
3
20
4
30
5

40 ≤ 60, so the left half is sorted. 20 isn't between 40 and 60: search the right.

Write find_in_rotated(times, target) in Python or findInRotated(times, target) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 26 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.