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.