#33MediumBinary Search

Search in Rotated Sorted Array

At least one half is always sorted — use that to decide where to search.

AmazonGoogleMicrosoftUberBloomberg

Problem Statement

Given a rotated sorted array nums (with no duplicates) and a target integer, return the index of target if it exists, otherwise return -1. You must write an algorithm with O(log n) runtime.

Examples

Example 1

Input:nums = [4,5,6,7,0,1,2], target = 0
Output:4

Example 2

Input:nums = [4,5,6,7,0,1,2], target = 3
Output:-1

Constraints

  • 1 ≤ nums.length ≤ 5000
  • −10⁴ ≤ nums[i], target ≤ 10⁴
  • All values are unique.

Solutions

1
Linear Search
TimeO(n)SpaceO(1)

Scan the array for target. O(n). Ignores the sorted property.

Visual Animation
def search(nums, target):
    try: return nums.index(target)
    except: return -1

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Binary Search to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems