Leetcode 33: Search in Rotated Sorted Array

grid47
grid47
Exploring patterns and algorithms
Nov 3, 2024 7 min read

A rotating spiral of light, revealing new paths and points of connection.
Solution to LeetCode 33: Search in Rotated Sorted Array Problem

You are given a sorted array ’nums’ which may have been rotated at an unknown pivot. Your task is to search for a target value in this rotated array. Return the index of the target if found, or -1 if not found. The solution must have a runtime complexity of O(log n).
Problem
Approach
Steps
Complexity
Input: The input is a rotated sorted array 'nums' of distinct integers, followed by the target value to search for.
Example: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Constraints:
• 1 <= nums.length <= 5000
• -104 <= nums[i] <= 104
• All values of nums are unique.
• nums is a rotated sorted array.
• -104 <= target <= 104
Output: The output is the index of the target in the rotated array if it exists, otherwise return -1.
Example: For nums = [4, 5, 6, 7, 0, 1, 2], target = 0, the output is 4.
Constraints:
Goal: The goal is to search for the target value in the rotated array efficiently using binary search.
Steps:
• Use binary search to find the pivot where the rotation occurs.
• Determine which half of the array is sorted, and narrow down the search to that half.
• Adjust the search range depending on whether the target is within the sorted half.
Goal: The array is rotated at some unknown index, and the array contains distinct elements. We need to ensure that the solution operates in O(log n) time.
Steps:
• The array contains at least one element.
• The array length is between 1 and 5000.
• Each element is distinct.
Assumptions:
• The array has been rotated, and the array is sorted in ascending order before the rotation.
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Explanation: The array is rotated at index 3, so the target value 0 is found at index 4 in the rotated array.

Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Explanation: The target value 3 does not exist in the array, so the output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus