Data Structures & Algorithms Binary Search
💡
Exercise 52

Search Rotated Array 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Search for a target in a rotated sorted array. Return its index or -1 if not found. You must achieve O(log n).

nums = [4,5,6,7,0,1,2], target = 0 → 4 nums = [4,5,6,7,0,1,2], target = 3 → -1

The trick: at any mid point, one half is always sorted. Check if target falls in the sorted half. If yes, search there. Otherwise, search the other half.

  • If nums[left] <= nums[mid]: left half is sorted
  • Check if target is in [nums[left], nums[mid]]
  • Otherwise, right half is sorted — apply similar logic
📋 Instructions
Implement `search(nums, target)` for a rotated sorted array. Test with: - `search([4,5,6,7,0,1,2], 0)` → 4 - `search([4,5,6,7,0,1,2], 3)` → -1 Print both results.
At each step, determine which half is sorted. If target is in the sorted half's range, search there. Otherwise search the other half.
🧪 Test Cases
Input
search([4,5,6,7,0,1,2], 0)
Expected
4
Test case 1
Input
search([4,5,6,7,0,1,2], 3)
Expected
-1
Boundary value
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.