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.