Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 35 · Basics / Lower & Upper Bound

Search Insert Position

LeetCode 35 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

When the search fails, low is the insert position.

எளிதுArrayBinary Search
LeetCode இல் திற ↗

நான் Search Insert Position (LeetCode 35) ஐ இப்படித் தீர்த்தேன் — Basics / Lower & Upper Bound பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Standard binary search, with one extra observation: if the target isn't present, the loop ends with low pointing at the first element larger than the target — exactly where it should be inserted.

Approach

  1. 1

    Binary search for target.

  2. 2

    Found → return mid.

  3. 3

    Not found → return low.

நான் எப்படித் தீர்த்தேன்

Binary search (lower bound)PythonO(log n) time
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        low = 0
        high= len(nums)-1
        while low<=high:
            mid = (low+high)//2
            if nums[mid]==target:
                return mid
            if nums[mid]>=target:
                high=mid-1
            else:
                low=mid+1
        return low
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Search Insert Position — அடிக்கடி கேட்கப்படும் கேள்விகள்

Search Insert Position பின்னாலுள்ள intuition என்ன?

Standard binary search, with one extra observation: if the target isn't present, the loop ends with low pointing at the first element larger than the target — exactly where it should be inserted.

Search Insert Position (LeetCode 35) ஐ எப்படித் தீர்ப்பது?

1. Binary search for target. 2. Found → return mid. 3. Not found → return low.

Search Insert Position இன் time மற்றும் space complexity என்ன?

Time: O(log n). Space: O(1). (Accepted approach: Binary search (lower bound).)

Search Insert Position இல் பொதுவான தவறுகள் என்ன?

Returning high would give the index before the insert slot.