Search Rotated Array
JavaScript
medium
25 mins
You are given an array of distinct integers sorted in ascending order, then rotated at an unknown pivot (e.g., [0,1,2,4,5,6,7] becomes [4,5,6,7,0,1,2]).
Implement a function to search for a target value in this rotated array. If found, return its index. If not found, return -1.
-
Input:
nums(number[]): Rotated sorted array of distinct integerstarget(number): The value to search
-
Output:
- (number): The index of the target in the array or
-1if not found
- (number): The index of the target in the array or
Example Inputs & Outputs
// Example 1: searchRotatedArray([4,5,6,7,0,1,2], 0); → 4 // Example 2: searchRotatedArray([4,5,6,7,0,1,2], 3); → -1 // Example 3: searchRotatedArray([1], 0); → -1
Constraints & Edge Cases
- Time complexity must be O(log n)
- All integers in the array are distinct
- The array is not empty
- Array may or may not be rotated
- The target may not be present
- Array of length 1 should return
0or-1correctly
Companies:
cisco
yahoo
intel
oyo
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
