Find First and Last Position of Element in Sorted Array
LeetCode 34 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Two biased binary searches.
मैंने Find First and Last Position of Element in Sorted Array (LeetCode 34) ऐसे हल किया — Basics / Lower & Upper Bound पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Run binary search twice. When you hit the target, don't stop: record it and keep searching left for the first position, or right for the last position.
Approach
- 1
First: on a match, save mid and set high = mid − 1.
- 2
Last: on a match, save mid and set low = mid + 1.
- 3
Return [first, last] (−1 if absent).
मैंने कैसे हल किया
Lower + upper bound searchesPythonO(log n) time
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def getFirstPosition():
ans=-1
low = 0
high=len(nums)-1
while low<=high:
mid = (low+high)//2
if nums[mid]==target:
ans = mid
high = mid-1
elif nums[mid]>target:
high = mid-1
else:
low = mid+1
return ans
def getLastPosition():
ans=-1
low = 0
high=len(nums)-1
while low<=high:
mid = (low+high)//2
if nums[mid]==target:
ans = mid
low = mid+1
elif nums[mid]>target:
high = mid-1
else:
low = mid+1
return ans
first = getFirstPosition()
last = getLastPosition()
return [first,last]Find First and Last Position of Element in Sorted Array — अक्सर पूछे जाने वाले प्रश्न
Find First and Last Position of Element in Sorted Array के पीछे intuition क्या है?
Run binary search twice. When you hit the target, don't stop: record it and keep searching left for the first position, or right for the last position.
Find First and Last Position of Element in Sorted Array (LeetCode 34) कैसे हल करें?
1. First: on a match, save mid and set high = mid − 1. 2. Last: on a match, save mid and set low = mid + 1. 3. Return [first, last] (−1 if absent).
Find First and Last Position of Element in Sorted Array की time और space complexity क्या है?
Time: O(log n)। Space: O(1)। (Accepted approach: Lower + upper bound searches।)
Find First and Last Position of Element in Sorted Array में आम गलतियाँ क्या हैं?
A linear scan from one hit is O(n) in the worst case.