ExamAdda Logo

Search in Rotated Sorted Array

Easy

Given an integer array nums sorted in ascending order and rotated at an unknown pivot, and an integer target, return the index of target if it exists in nums.

Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

All values in nums are distinct.

Example 1

Input

n = 7
nums = [4, 5, 6, 7, 0, 1, 2]
target = 0

Output

4

Explanation

The target 0 is present at index 4.

Example 2

Input

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

Output

-1

Explanation

The target 3 does not exist in the array.

Constraints

1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
All values in nums are distinct.
nums is sorted in ascending order and then rotated.
-10^4 <= target <= 10^4

Hints:

Hint 1

At every step, at least one half of the array is normally sorted.

Hint 2

Check whether the left half is sorted:

nums[left] <= nums[mid]

 

Then determine whether the target lies inside that sorted range.

Otherwise, search the other half.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 22, 2026

Last updated

Aug 22, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output