
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)
Editorial
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. |
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