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.