Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 34 · Basics / Lower & Upper Bound

Find First and Last Position of Element in Sorted Array

LeetCode 34 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Two biased binary searches.

ಮಧ್ಯಮArrayBinary Search
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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. 1

    First: on a match, save mid and set high = mid − 1.

  2. 2

    Last: on a match, save mid and set low = mid + 1.

  3. 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.