Skip to content
AI360Xpert
Back to Binary Search
Medium

Search in Rotated Sorted Array

There is an integer array `nums` sorted in ascending order (with distinct values). Prior to being passed to your function, `nums` is possibly rotated at an unknown pivot index. 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.

Examples

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

Constraints

  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values of nums are unique.
  • nums is an ascending array that is possibly rotated.
  • -10^4 <= target <= 10^4

Approach

Iterate through the array. If the current element matches the target, return its index. If the loop completes, return -1.

Complexity Analysis

Time Complexity
O(n)
Space Complexity
O(1)

This approach does not meet the O(log n) time complexity requirement.

Solution.java
class Solution {    public int search(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            if (nums[i] == target) {                return i;            }        }        return -1;    }}