MEDIUM NC#32 Blind #8 Binary Search

33. Search in Rotated Sorted Array

📖 Problem

There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly left rotated at an unknown pivot index k. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • Array methods (`push`, `pop`, `shift`, `slice`)
  • Object/Map/Set usage patterns
  • Function parameter and return typing
  • Midpoint overflow-safe math
  • Loop invariants
  • Monotonic condition design

Logical Thinking Concepts

  • Define invariants before coding
  • Check edge cases first (`[]`, single element, duplicates)
  • Estimate time/space before implementation
  • Apply Binary Search reasoning pattern

💡 Approach

  • At least one half of rotated array is always sorted
  • Determine which half is sorted by comparing left and mid elements
  • Check if target lies in sorted half, otherwise search the other half
  • Time: O(log n), Space: O(1)

🛠️ Hints & Pitfalls

Hints

  • At least one half of rotated array is always sorted
  • Determine which half is sorted by comparing left and mid elements
  • Check if target lies in sorted half, otherwise search the other half

Common Pitfalls

  • Time: O(log n), Space: O(1)

🧪 Test Cases

Hidden tests on submit: 3

Test Case 1
Not run
Input:
search([4,5,6,7,0,1,2], 0);
Expected:
4
Test Case 2
Not run
Input:
search([4,5,6,7,0,1,2], 3);
Expected:
-1
Test Case 3
Not run
Input:
search([1], 0);
Expected:
-1

📝 Code Editor

📚 Reference Solution

⌘K Search ⌘↩ Run ⌘S Submit