Search in Rotated Sorted Array β Python
π Search in Rotated Sorted Array β Python (Binary Search) Hi All, Today I solved an important problem: Search in Rotated Sorted Array using Binary Search. π Problem Statement Given a sorted array...

Source: DEV Community
π Search in Rotated Sorted Array β Python (Binary Search) Hi All, Today I solved an important problem: Search in Rotated Sorted Array using Binary Search. π Problem Statement Given a sorted array that is rotated at some pivot, find the index of a target element. π If not found, return -1. π Examples Example 1: nums = [4, 5, 6, 7, 0, 1, 2] target = 0 Output: 4 Example 2: nums = [4, 5, 6, 7, 0, 1, 2] target = 3 Output: -1 Example 3: nums = [1] target = 0 Output: -1 π‘ Key Insight π Even though the array is rotated: One half of the array is always sorted π‘ Approach πΉ Modified Binary Search Find mid Check which half is sorted: Left half sorted β check if target is inside Right half sorted β check if target is inside π§ Step-by-Step Logic If nums[left] <= nums[mid] β Left part is sorted Else β Right part is sorted Then: Decide where to search next π» Python Code def search(nums, target): left = 0 right = len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid]