Search Insert Position
LeetCode 35 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
When the search fails, low is the insert position.
আমি 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
Binary search for target.
- 2
Found → return mid.
- 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 lowSearch 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.