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.