Skip to content
mlmentorship

Search in Rotated Sorted Array

Identify one sorted half, use exact endpoint bounds to retain a target, and handle duplicate ambiguity without promising logarithmic progress.

Published · 11 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Search in Rotated Sorted Array

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An integer list nums obtained by rotating a strictly increasing list, and an integer target. Output. Return the target's zero-based index in the supplied rotated list, or -1 if absent. Rules. Values are distinct, and zero rotation is valid. Do not sort or otherwise modify the input; returned positions refer to its current order. Empty input returns -1. Supporting duplicate values is a changed contract below. Example. For [4, 5, 6, 7, 0, 1, 2] and target 0, return 4. Target 3 in that list returns -1.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Keep the interval containing target 0 by identifying one sorted half at each probe.

Problem trace

A sorted half can be discarded when its bounds exclude the target

Worked example: identify the sorted half before testing whether it contains the targetFor target 0, the sorted half (4,5,6,7) is ineligible. Keep opposite half (0,1,2).One comparison removes a region, notjust one itemMiddle seven ends the sorted lefthalf40516273041526Zero is outside four through seven:keep the other half40516273041526Original positions stay fixed;crossed items cannot contain theanswer.
Read it this way: For target 0, the sorted half (4,5,6,7) is ineligible. Keep opposite half (0,1,2). Would target five justify discarding this same left half?
Full interview answer 11 min read

Find a target’s original position in a distinct sorted array whose starting position may have been rotated.

Problem

Input. An integer list nums obtained by rotating a strictly increasing list, and an integer target.

Output. Return the target’s zero-based index in the supplied rotated list, or -1 if absent.

Rules. Values are distinct, and zero rotation is valid. Do not sort or otherwise modify the input; returned positions refer to its current order. Empty input returns -1. Supporting duplicate values is a changed contract below.

Example. For [4, 5, 6, 7, 0, 1, 2] and target 0, return 4. Target 3 in that list returns -1.

Picture

Reuse the inclusive candidate interval: if the target exists, its index remains in [left,right].

First compare nums[middle] with target. Equality returns immediately, so later tests can exclude the midpoint.

At most one rotation drop exists. If nums[left] <= nums[middle], the left half is sorted; otherwise, the right half is sorted.

Known sorted halfTarget fits whenRetain if it fits
left..middlenums[left] <= target < nums[middle][left,middle-1]
middle..rightnums[middle] < target <= nums[right][middle+1,right]

If the target does not fit the sorted half, retain the other half. Neither update can discard a possible occurrence.

For [4,5,6,7,0,1,2] and target zero:

Candidate intervalProbeDecision
[0,6]Index 3 has 7Sorted values 4 through 7 exclude zero; retain [4,6]
[4,6]Index 5 has 1Sorted values 0 through 1 include zero; retain [4,4]
[4,4]Index 4 has 0Return 4

Trace L, m, and R mean left, middle, and right.

Problem trace

A sorted half can be discarded when its bounds exclude the target

Input and goalFind a target in a sorted array that was rotated once.
Reject the sorted halfleft=0, right=6, middle=3. The left half is sorted, but zero is outside [4,7), so set left=4.
L405162m730415R26
target0sortedindices 0..3decision0 not in [4, 7): left = 4
Candidate indices for target 0: 0 through 6. This is the initial candidate range; no earlier state is assumed.Candidate indices; target 00123456Startcandidate indices [0,6]
L
0
m
3
R
6

Recognize it
The array was sorted and rotated once with distinct values, so although the whole interval may cross the pivot, at least one side of middle remains sorted.
Keep true
If target 0 exists, it remains in inclusive [left, right]. A half is discarded only after its sorted value range proves whether target can occur there.
Reuse it
When a monotone ordering is disrupted once, find a locally ordered region and use its endpoint values to make the same safe-elimination argument as ordinary binary search.
left=0, right=6, middle=3. The left half is sorted, but zero is outside [4,7), so set left=4. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why may indices 0 through 3 be discarded even though they are the sorted half?
Reference drawing

Problem trace

A sorted half can be discarded when its bounds exclude the target

Worked example: identify the sorted half before testing whether it contains the targetFor target 0, the sorted half (4,5,6,7) is ineligible. Keep opposite half (0,1,2).One comparison removes a region, notjust one itemMiddle seven ends the sorted lefthalf40516273041526Zero is outside four through seven:keep the other half40516273041526Original positions stay fixed;crossed items cannot contain theanswer.
Execution trace
Input and goalFind a target in a sorted array that was rotated once.
Reject the sorted halfleft=0, right=6, middle=3. The left half is sorted, but zero is outside [4,7), so set left=4.
L405162m730415R26
target0sortedindices 0..3decision0 not in [4, 7): left = 4
Candidate indices for target 0: 0 through 6. This is the initial candidate range; no earlier state is assumed.Candidate indices; target 00123456Startcandidate indices [0,6]
L
0
m
3
R
6

Recognize it
The array was sorted and rotated once with distinct values, so although the whole interval may cross the pivot, at least one side of middle remains sorted.
Keep true
If target 0 exists, it remains in inclusive [left, right]. A half is discarded only after its sorted value range proves whether target can occur there.
Reuse it
When a monotone ordering is disrupted once, find a locally ordered region and use its endpoint values to make the same safe-elimination argument as ordinary binary search.
left=0, right=6, middle=3. The left half is sorted, but zero is outside [4,7), so set left=4. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why may indices 0 through 3 be discarded even though they are the sorted half?
Read it this way: For target 0, the sorted half (4,5,6,7) is ineligible. Keep opposite half (0,1,2). Would target five justify discarding this same left half?

Code

def search_rotated(nums: list[int], target: int) -> int:
   left, right = 0, len(nums) - 1

   while left <= right:
      middle = (left + right) // 2
      if nums[middle] == target:
         return middle

      if nums[left] <= nums[middle]:
         if nums[left] <= target < nums[middle]:
            right = middle - 1
         else:
            left = middle + 1
      elif nums[middle] < target <= nums[right]:
         left = middle + 1
      else:
         right = middle - 1

   return -1

Each unsuccessful probe removes its midpoint and roughly half the candidates. Distinct input needs comparisons and auxiliary space.

With duplicates, [1,0,1,1,1] and target zero incorrectly return -1. Equal left/middle values no longer prove the left half is sorted.

Unlike minimum search, this loop checks midpoint equality before discarding it.

Change Ambiguity or Output

Start from search_rotated. Two adjustable parts are the ordering evidence and the result representation.

  1. Permit duplicates.

    New task: Return an occurrence in a rotated nondecreasing array, or -1.

    Picture and change: Keep the first equality check. If left, middle, and right values agree, the endpoint values are also known nonmatches.

    Discard only those endpoints; their equality does not locate the rotation drop.

    Code: Complete replacement:

    def search_rotated_duplicates(nums, target):
       left, right = 0, len(nums) - 1
       while left <= right:
          middle = (left + right) // 2
          if nums[middle] == target:
             return middle
          if nums[left] == nums[middle] == nums[right]:
             left += 1
             right -= 1
          elif nums[left] <= nums[middle]:
             if nums[left] <= target < nums[middle]:
                right = middle - 1
             else:
                left = middle + 1
          elif nums[middle] < target <= nums[right]:
             left = middle + 1
          else:
             right = middle - 1
       return -1

    Check: [1,0,1,1,1], target zero, returns index one. [1,1,1], target two, returns -1.

    No first-occurrence guarantee is added. All-equal absent input can require work; auxiliary space remains .

    Use when: Duplicate values remove the evidence needed to discard a complete half.

  2. Return membership only.

    New task: Report a Boolean rather than an index, under the original distinctness contract.

    Picture and change: Keep every search decision. Convert the returned missing sentinel explicitly.

    Code: Place this complete wrapper after the retained search_rotated definition.

    def contains_rotated(nums, target):
       return search_rotated(nums, target) != -1

    Check: [1,2,3], target one, returns True despite its zero index. Empty input returns False.

    Using bool(index) would treat index zero as false and missing -1 as true.

    Use when: Only the output representation changes. The reference’s assumptions and complexity remain unchanged.

Rebuild the Evidence

Why does the duplicate variant lose logarithmic worst-case progress?

Answer: Equal boundary and midpoint values may justify removing only two positions, not a half. Correctness survives; halving does not.