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.