Search in Rotated Sorted Array
LeetCode 33 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Identify the sorted half; test whether the target lies in it.
मैंने 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
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.
मैंने कैसे हल किया
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 -1Search 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.