Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 33 · Rotated Sorted Array

Search in Rotated Sorted Array

LeetCode 33 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Identify the sorted half; test whether the target lies in it.

మధ్యస్థంArrayBinary Search
LeetCode లో తెరవండి ↗

నేను Search in Rotated Sorted Array (LeetCode 33) ను ఇలా పరిష్కరించాను — Rotated Sorted Array ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

After rotation, at least one half around mid is still sorted. Check which one, and whether the target falls inside that sorted half's range — that tells you which side to keep.

Approach

  1. 1

    mid matches → return.

  2. 2

    If nums[low] ≤ nums[mid], the left half is sorted: keep it if target ∈ [nums[low], nums[mid]).

  3. 3

    Otherwise the right half is sorted: keep it if target ∈ (nums[mid], nums[high]].

  4. 4

    Not found → −1.

నేను ఎలా పరిష్కరించాను

Modified binary searchPythonO(log n) time
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        #binary search
        low=0
        high =len(nums)-1
        while low<=high:
            mid = (low+high)//2
            if nums[mid]==target:
                return mid
            if nums[low]<=nums[mid]:
                #left half is sorted
                if target>=nums[low] and target<nums[mid]:
                    high = mid-1
                else:
                    low = mid+1
            else:
                #right half is sorted
                if target>nums[mid] and target<=nums[high]:
                    low=mid+1
                else:
                    high = mid-1
        return -1
స్టెప్-త్రూ లోడ్ అవుతోంది…

Search in Rotated Sorted Array — తరచూ అడిగే ప్రశ్నలు

Search in Rotated Sorted Array వెనుక ఉన్న intuition ఏమిటి?

After rotation, at least one half around mid is still sorted. Check which one, and whether the target falls inside that sorted half's range — that tells you which side to keep.

Search in Rotated Sorted Array (LeetCode 33) ను ఎలా పరిష్కరించాలి?

1. mid matches → return. 2. If nums[low] ≤ nums[mid], the left half is sorted: keep it if target ∈ [nums[low], nums[mid]). 3. Otherwise the right half is sorted: keep it if target ∈ (nums[mid], nums[high]]. 4. Not found → −1.

Search in Rotated Sorted Array యొక్క time, space complexity ఎంత?

Time: O(log n). Space: O(1). (Accepted approach: Modified binary search.)

Search in Rotated Sorted Array లో సాధారణ పొరపాట్లు ఏమిటి?

Use ≤ in nums[low] ≤ nums[mid] for two-element ranges.