Search in Rotated Sorted Array - Array - Medium - LeetCode
💻 coding

Search in Rotated Sorted Array - Array - Medium - LeetCode

1 min read 185 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves searching for a target in a rotated sorted array.
  • 2The solution uses a binary search approach to find the rotation point and the target.
  • 3Time complexity is O(log n) and space complexity is O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves searching for a target in a rotated sorted array."

Search in Rotated Sorted Array - Array - Medium - LeetCode

You are given an integer array nums sorted in ascending order, and an integer target.

Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

If target is found in the array return its index, otherwise, return -1.

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 Example 3:

Input: nums = [1], target = 0 Output: -1

Constraints:

1 <= nums.length <= 5000 -10^4 <= nums[i] <= 10^4 All values of nums are unique. nums is guranteed to be rotated at some pivot. -10^4 <= target <= 10^4

public class Solution {
 public int Search(int[] nums, int target) {
 int low = 0;
 int high = nums.Length-1;
 int len = nums.Length;
 while(low<high){
 int mid = low+(high-low)/2;
 if(nums[mid]>nums[high]){
 low=mid+1;
 }
 else{
 high=mid;
 }
 }
 
 int rotation = low;
 
 low=0;
 high = nums.Length-1;
 while(low<=high){
 int mid = low+(high-low)/2;
 int actualMid = (mid + rotation)%len;
 if(nums[actualMid]==target){
 return actualMid;
 }
 else if(nums[actualMid]<target){
 low=mid+1;
 }
 else{
 high=mid-1;
 } 
 }
 
 return -1;
 }
 
}

Time Complexity: O(logn)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 24 October 2020 · 1 min read · 185 words

Part of AskGif Blog · coding

You might also like