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.