
Problem
Solution
Submissions
Search in Rotated Sorted Array
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript function to search for a target value in a rotated sorted array without using any built-in search methods. A rotated sorted array is a sorted array that has been rotated at some pivot point. The function should return the index of the target if found, or -1 if not found. The solution should be efficient with O(log n) time complexity.
Example 1
- Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
- Output: 4
- Explanation:
- The array is rotated at index 4 (original: [0,1,2,4,5,6,7]).
- We need to find the target value 0.
- Using binary search, we identify which half contains the target.
- The target 0 is found at index 4. Return the index 4.
- The array is rotated at index 4 (original: [0,1,2,4,5,6,7]).
Example 2
- Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3
- Output: -1
- Explanation:
- The array is rotated and we're searching for target 3.
- Using binary search, we check both halves of the array.
- The left half [4,5,6,7] doesn't contain 3.
- The right half [0,1,2] doesn't contain 3.
- Since 3 is not found in the array, return -1.
- The array is rotated and we're searching for target 3.
Constraints
- All values in the array are unique
- The array was originally sorted in ascending order
- The array has been rotated at some pivot point
- You cannot use built-in search methods like indexOf() or find()
- 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 binary search approach to achieve O(log n) time complexity
- Identify which half of the array is sorted at each step
- Check if the target lies within the sorted half
- Adjust the search boundaries based on the sorted half
- Handle the rotation by comparing with the middle element