Search in Rotated Sorted Array

Program for Searching in a Rotated Sorted Array Problem

You are given a sorted array that has been rotated between 1 and n times. For example:

If the array [1,2,3,4,5,6] is rotated 4 times, it becomes [3,4,5,6,1,2].

If rotated 6 times, it stays as [1,2,3,4,5,6].
Your task is to find the index of a given target number in this rotated array. If the target is not found, return -1.

You can assume that all elements in the array are unique.

While finding the target in O(n) time is straightforward, you need to design an algorithm that works in O(logn) time.

Search in Rotated Sorted Array

Constraints:

  • 1 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -1000 <= target <= 1000

Program for Searching in a Rotated Sorted Array Solution

Recommendation for Time and Space Complexity – You should aim for a solution with O(logn) time and O(1) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

A brute force solution would be to do a linear search on the array to find the target element. This would be an O(n) solution. Can you think of a better way? Maybe an efficient searching algorithm is helpful.

Hint 2 :

A rotated sorted array forms two sorted segments separated by a pivot point. For example, [3,4,1,2] has two segments: [3,4] and [1,2]. To find a target efficiently, first locate the pivot using binary search, then perform binary search on the appropriate segment.

There are mainly 4 approach to solve this problem-

  1. Brute Force Method
  2. Binary Search Method
  3. Binary Search Method(Two Pass)
  4. Binary Search Method(One Pass)

1. Brute Force Method

Iterate through the entire array to find the target element, resulting in an O(n) solution.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

2. Binary Search Method

Find the pivot point where the array is rotated, then perform binary search separately on the two sorted segments.

  • Time complexity: O(log n)
  • Space complexity: O(1)

Code

3. Binary Search Method(Two Pass)

First, locate the pivot using binary search, then conduct a second binary search in the appropriate half to find the target.

  • Time complexity: O(log n)
  • Space complexity: O(1)

Code

4. Binary Search Method(One Pass)

Modify binary search logic to account for the rotation, adjusting search conditions dynamically to find the target in a single pass.

  • Time complexity: O(log n)
  • Space complexity: O(1)

Code

More Articles