ASSIGNMENT 20
Search in a Rotated Sorted Array (O(log n) Binary Search) Searching in a rotated array might look tricky at first β but with the right approach, it becomes elegant and efficient π₯ Letβs break it d...

Source: DEV Community
Search in a Rotated Sorted Array (O(log n) Binary Search) Searching in a rotated array might look tricky at first β but with the right approach, it becomes elegant and efficient π₯ Letβs break it down π π Problem Statement You are given a sorted array that has been rotated at some unknown index. π Your task is to find the index of a target element. β οΈ Constraints: All elements are distinct Must run in O(log n) time If target not found β return -1 π§ͺ Examples Example 1 Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2 Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Example 3 Input: nums = [1], target = 0 Output: -1 π‘ Key Insight Even though the array is rotated, one half is always sorted. π At any point: Either the left half is sorted Or the right half is sorted We use this property to apply Binary Search. π§ Algorithm Strategy Find mid Check which half is sorted: If nums[low] <= nums[mid] β Left half is sorted Else β Right half is sorted Decide where target lie