Skip to content
Algorithms for Beginners

Problems / Binary search

Search a rotated list

medium

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

A sorted list of different numbers was cut at some point, and the two pieces were swapped. For example, [1, 2, 4, 5, 6, 7, 9] cut after the 5 becomes [6, 7, 9, 1, 2, 4, 5]. It might also not have been cut at all.

Given the result, nums, return the position of target, or -1 if it isn't there.

Examples

  1. Example 1

    Input
    nums = [6, 7, 9, 1, 2, 4, 5], target = 2
    Output
    4

    2 is at position 4.

  2. Example 2

    Input
    nums = [6, 7, 9, 1, 2, 4, 5], target = 8
    Output
    -1
  3. Example 3

    Input
    nums = [1, 3, 5], target = 5
    Output
    2

    This list wasn't cut at all.

Rules

  • nums has between 0 and 1,000,000 different numbers.
  • Aim for O(log n): binary search, adapted.
Words on this page, in plain English (4)Open if any word is new to you
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Index (position)
Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
O(log n): logarithmic time
The work grows very slowly, because each step throws away half. A million items need only about 20 steps.
Sorted
In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function rotatedSearch(nums, target) {
  // Return the position of target, or -1.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in binary search