Search in Rotated Sorted Array

Problem Summary

Key Observations

(Patterns, constraints, or hints in the problem statement.)

Approach Taken

(Step-by-step logic or pseudocode before coding.)

Why This Works

(Explain the core reason the solution is correct.)

Main Concepts Used

(Mark the CS concepts or algorithms used.)

Time & Space Complexity

Code

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        l, r = 0, len(nums) - 1

        while l <= r:
            m = (l + r) // 2
            left = nums[l]
            right = nums[r]
            mid = nums[m]

            if target == mid:
                return m

            if left <= mid: #left is sorted
                if left <= target <= mid:
                    r = m - 1
                else:
                    l = m + 1
            else: # right is sorted
                if mid <= target <= right:
                    l = m + 1
                else:
                    r = m - 1
        return -1