Search in Rotated Sorted Array
Real-world version: Shifted Catalogue LookupThe statement here is our own: the same inputs, outputs and technique.
A catalogue drawer holds cards stamped with reference numbers, no two alike. Numbering starts below zero for retired stock, so a reference number may be negative.
The cards were filed strictly increasing from front to back. Afterwards a clerk cut the drawer at one point, lifted out the block in front of the cut and set it down behind the remaining block, leaving both blocks in their own order. If the clerk happened to cut right at the very front, nothing actually moved and the drawer is still plainly increasing.
cards is the drawer as it reads today, front to back. Given a reference number wanted, return the index of the card carrying it, or -1 when the drawer holds no such card. Reference numbers never repeat, so at most one index can be the answer.
Pulling a card out to read it is the expensive step, so the number of cards you inspect has to grow only with the logarithm of the drawer size. Working front to back through the drawer is too many reads.
Examples
Example 1
- Input
- cards = [7, 9, 12, -5, 1, 4], wanted = 1
- Output
- 4
Filed in order the drawer would read -5, 1, 4, 7, 9, 12; the clerk cut before 7 and moved the block -5, 1, 4 to the back. Card 1 now sits at index 4.
Example 2
- Input
- cards = [-3, 0, 8], wanted = 8
- Output
- 2
The cut fell at the very front, so nothing moved and the drawer still increases throughout. Card 8 is last, at index 2.
Example 3
- Input
- cards = [7, 9, 12, -5, 1, 4], wanted = 6
- Output
- -1
The number 6 would slot between 4 and 7 in the filed order, but no card carries it, so the drawer reports nothing.
Constraints
- 1 <= cards.length <= 5000
- -10^4 <= cards[i] <= 10^4
- Every reference number in cards is distinct
- cards is an increasing filing whose front block may have been moved to the back
- -10^4 <= wanted <= 10^4
- The lookup must run in O(log n) time
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def locate_card(cards: list[int], wanted: int) -> int:public int locateCard(int[] cards, int wanted)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 16 test cases: 16 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's