Tensorum
YouTubeশেখা শুরু করুন
LeetCode 81 · Rotated Sorted Array

Search in Rotated Sorted Array II

LeetCode 81 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

nums[low] == nums[mid] == nums[high] ⇒ low++, high−−.

মাঝারিArrayBinary Search
LeetCode-এ খুলুন ↗

আমি Search in Rotated Sorted Array II (LeetCode 81) এভাবে সমাধান করেছি — Rotated Sorted Array প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।

নিচের বিবরণ ইংরেজিতে।

Intuition

Like the distinct version, but duplicates can hide which half is sorted (e.g. low, mid and high all equal). In that ambiguous case shrink both ends by one and retry.

Approach

  1. 1

    mid matches → True.

  2. 2

    Ambiguous triple → shrink both ends.

  3. 3

    Otherwise apply the sorted-half test.

  4. 4

    Not found → False.

আমি কীভাবে সমাধান করেছি

Binary search with duplicate shrinkPythonO(log n) avg
class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        low = 0
        high=len(nums)-1
        while low<=high:
            mid = (low+high)//2
            if nums[mid]==target:
                return True
            if nums[low]==nums[mid] and nums[mid]==nums[high]:
                low = low+1
                high= high-1
                continue
            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:
                if target>nums[mid] and target<=nums[high]:
                    low=mid+1
                else:
                    high=mid-1
        return False
স্টেপ-থ্রু লোড হচ্ছে…

Search in Rotated Sorted Array II — সাধারণ প্রশ্ন

Search in Rotated Sorted Array II-এর পেছনে intuition কী?

Like the distinct version, but duplicates can hide which half is sorted (e.g. low, mid and high all equal). In that ambiguous case shrink both ends by one and retry.

Search in Rotated Sorted Array II (LeetCode 81) কীভাবে সমাধান করবেন?

1. mid matches → True. 2. Ambiguous triple → shrink both ends. 3. Otherwise apply the sorted-half test. 4. Not found → False.

Search in Rotated Sorted Array II-এর time আর space complexity কত?

Time: O(log n) average, O(n) worst। Space: O(1)। (Accepted approach: Binary search with duplicate shrink।)

Search in Rotated Sorted Array II-এ সাধারণ ভুলগুলো কী?

Duplicates make the worst case linear — that's unavoidable.