
Searching in a Rotated Sorted Array Using Modified Binary Search in Python
Problem Explanation You are given a sorted array nums that has been rotated at some unknown index . Your task is to find the index of a target element . If the target is not present, return -1 . Example: Input: nums = [4,5,6,7,0,1,2] , target = 0 Output: 4 Input: nums = [4,5,6,7,0,1,2] , target = 3 Output: -1 Input: nums = [1] , target = 0 Output: -1 Method Used: Modified Binary Search Idea Even though the array is rotated, one half is always sorted . So: Check which half is sorted Decide where the target lies Continue binary search Why This Method? Time complexity: O(log n) Efficient even after rotation No need to actually rotate back Python Code with Explanation class Solution : def search ( self , nums , target ): Defines the function. left = 0 right = len ( nums ) - 1 Initialize search range. while left <= right : Run binary search loop. mid = ( left + right ) // 2 Find middle index. if nums [ mid ] == target : return mid If target found, return index. if nums [ left ] <= nums [ mi
Continue reading on Dev.to Python
Opens in a new tab


