Night Guard Round

Mediumbinary searchAlso known as Search in Rotated Sorted Array

A hotel's corridor is a loop. The rooms along it are numbered in increasing order, and after the highest-numbered room the loop comes back to the lowest. Each night the guard starts the round at a different room and walks the whole loop once, ticking off rooms on a sheet.

So tonight's sheet might read 410, 415, 502, 517, 108, 112, 230, 301: sorted, except that it wraps around once. A guest calls about room 112. Where on the sheet is it?

Your task

Write findRoom(round, room). round holds distinct room numbers: a strictly increasing list that may have been rotated (some prefix moved to the back). Return the index of room in round, or -1 if it is not there.

The rotation may be zero, so the list may be fully sorted. An empty list returns -1. Aim for O(log n).

findRoom(round: int[], room: int) → int

Examples

Example 1
Input
round = [410, 415, 502, 517, 108, 112, 230, 301]
room = 112
Output
5
Why

The sheet climbs from 410 to 517, wraps, and climbs again from 108 to 301. Room 112 is in the second climb, at index 5.

Example 2
Input
round = [410, 415, 502, 517, 108, 112, 230, 301]
room = 300
Output
-1
Why

300 would belong in the second climb between 230 and 301, but there is no room 300.

Constraints

  • 0 ≤ round.length ≤ 100,000
  • 1 ≤ round[i], room ≤ 1,000,000
  • All room numbers are different; round is an increasing list rotated by some amount.
Start with brute force

Read the sheet from the top until you find the room. O(n), up to 100,000 checks.

Plain binary search does not work either: it assumes the whole list is sorted. Searching for 112 in the example, it sees 517 in the middle, decides 112 must be to the left, and never finds it.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code