DEV Community

Mubashir
Mubashir

Posted on

Search In Rotated Sorted Array

In this task, I worked on searching for a target element in a rotated sorted array.
A rotated array means a sorted array is shifted at some pivot point.

MY APPROACH
created a function that takes:

  • A rotated sorted array
  • A target value And returns the index of the target, or -1 if not found

LOGIC IMPLEMENTED
Instead of using normal search, I used a modified Binary Search.
Even though the array is rotated, one half is always sorted.

  • Find the middle element
  • Check which half is sorted: Left half sorted OR right half sorted
  • Check if target lies in that sorted half
  • Adjust search range accordingly

EXAMPLE
Input :nums = [4,5,6,7,0,1,2], target = 0
output : 4

class Solution:
    def search(self, nums, target):
        low = 0
        high = len(nums) - 1

        while low <= high:
            mid = (low + high) // 2

            if nums[mid] == target:
                return mid

            # Left half is sorted
            if nums[low] <= nums[mid]:
                if nums[low] <= target < nums[mid]:
                    high = mid - 1
                else:
                    low = mid + 1

            # Right half is sorted
            else:
                if nums[mid] < target <= nums[high]:
                    low = mid + 1
                else:
                    high = mid - 1

        return -1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)