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.