Tutorialspoint
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.
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.
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)
ArraysAlgorithmsGoldman SachsSamsung
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 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

Steps to solve by this approach:

 Step 1: Initialize left and right pointers for binary search.
 Step 2: Calculate the middle index and check if it equals the target.
 Step 3: Determine which half of the array is sorted (left or right).
 Step 4: Check if the target lies within the sorted half's range.
 Step 5: Adjust the search boundaries based on where the target might be.
 Step 6: Continue the binary search until the target is found or search space is exhausted.
 Step 7: Return the index if found, otherwise return -1.

Submitted Code :