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