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]