Tutorialspoint
Problem
Solution
Submissions

Search in Rotated Sorted Array

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to search for a target value in a rotated sorted array. Given a sorted array that has been rotated at some pivot unknown to you beforehand, and a target value, return the index of the target if it's in the array, or -1 if it's not. You may assume no duplicate values in the array.

Example 1
  • Input: nums = [4,5,6,7,0,1,2], target = 0
  • Output: 4
  • Explanation:
    • The array was rotated at pivot 4, making [0,1,2,4,5,6,7] into [4,5,6,7,0,1,2].
    • The target value 0 is at index 4.
Example 2
  • Input: nums = [4,5,6,7,0,1,2], target = 3
  • Output: -1
  • Explanation: The target value 3 is not in the array.
Constraints
  • 1 ≤ nums.length ≤ 5000
  • -10^4 ≤ nums[i] ≤ 10^4
  • All values of nums are unique
  • nums is a rotated sorted array
  • -10^4 ≤ target ≤ 10^4
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysAlgorithmsGoogleWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a modified binary search to solve this problem
  • In a normal binary search, you compare the middle element with the target
  • In this problem, first determine which half of the array is sorted
  • If the target is in the range of the sorted half, search there; otherwise, search in the other half
  • Continue the binary search process until you find the target or exhaust the search space

Steps to solve by this approach:

 Step 1: Initialize left and right pointers to the beginning and end of the array.
 Step 2: In each iteration of binary search, find the middle element.
 Step 3: If the middle element is the target, return its index.
 Step 4: Determine which half of the array is sorted by comparing nums[left] with nums[mid].
 Step 5: If the left half is sorted and the target falls within its range, search in the left half; otherwise, search in the right half.
 Step 6: If the right half is sorted and the target falls within its range, search in the right half; otherwise, search in the left half.
 Step 7: If the target is not found after the search, return -1.

Submitted Code :