Tutorialspoint
Problem
Solution
Submissions

Search in Rotated Sorted Array

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

Write a C program to search for a target value in a rotated sorted array. A rotated sorted array is an array that was once sorted in ascending order but has been rotated at some pivot point. For example, [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]. You need to find the index of the target value in the array, or -1 if it's not found. Your algorithm should have a time complexity of O(log n).

Example 1
  • Input: nums = [4,5,6,7,0,1,2], target = 0
  • Output: 4
  • Explanation: The original sorted array [0,1,2,4,5,6,7] was rotated at pivot point 4. The resulting array is [4,5,6,7,0,1,2]. We find that 0 is at index 4.
Example 2
  • Input: nums = [4,5,6,7,0,1,2], target = 3
  • Output: -1
  • Explanation: The array [4,5,6,7,0,1,2] does not contain the value 3. After searching through the entire array, we don't find the target.
Constraints
  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values in nums are unique
  • nums is guaranteed to be rotated at some pivot
  • -10^4 <= target <= 10^4
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysAlgorithmsShopifyTutorix
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 algorithm
  • In a standard binary search, we check if the middle element equals the target
  • In a rotated array, we first need to determine which half is sorted
  • If the left half is sorted, check if the target is within that range, otherwise search the right half
  • If the right half is sorted, check if the target is within that range, otherwise search the left half
  • Continue until you find the target or determine it doesn't exist

Steps to solve by this approach:

 Step 1: Use binary search but modify it to handle the rotation aspect of the array.
 Step 2: Find the middle element and check if it matches the target value.
 Step 3: Determine which half of the array is sorted (either left half or right half must be sorted).
 Step 4: If the left half is sorted (nums[left] <= nums[mid]), check if the target lies in this sorted range.
 Step 5: If the target is in the sorted range, narrow the search to that half; otherwise, search the other half.
 Step 6: If the right half is sorted (nums[mid] < nums[right]), apply similar logic to check if the target is in this range.
 Step 7: Continue narrowing the search range until we either find the target or determine it's not in the array.

Submitted Code :