⚡Flashcard Drill➔
NeetCode #261LC-35EasyBinary SearchNC 250
← Back to All Problems

#261 · #35 · Search Insert Position(搜索插入位置)

📌 Problem Statement & Constraints

Given a sorted array of distinct integers nums and a target, return the index where the target is, or where it should be inserted to keep the array sorted. Constraints: 1 <= nums.length <= 10^4, -10^4 <= nums[i], target <= 10^4.

💡 Core Algorithmic Approaches

  1. This is exactly the lower bound: the first index at which the value is at least the target.
  2. Binary search with lo = mid + 1 when nums[mid] < target, and hi = mid otherwise.
  3. The loop ends at lo == hi, which is the insertion point.
  4. Python's bisect_left implements precisely this, so the built-in is a legitimate answer.

💻 Benchmark Python3 Implementation

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        lo, hi = 0, len(nums)      # note: hi is exclusive here
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] < target:
                lo = mid + 1       # target must be to the right
            else:
                hi = mid           # mid is a candidate answer
        return lo


# Built-in equivalent
class Solution2:
    def searchInsert(self, nums: List[int], target: int) -> int:
        from bisect import bisect_left
        return bisect_left(nums, target)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(log n): the search space halves each iteration.
💾 Space Complexity
O(1): two indices.

⚠️ Interview Pitfalls & Follow-ups

  • Using hi = len(nums) - 1: the insertion point can be len(nums) (when the target is larger than every element), so the exclusive bound hi = len(nums) is needed.
  • Using hi = mid - 1: that would skip the candidate at mid; the correct form is hi = mid.
  • Returning mid: the loop ends at lo == hi, which is the answer.
  • Handling the empty array: lo = hi = 0 immediately returns 0, which is correct and needs no special case.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Binary Search Problems

中文速览与面试要点

搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。请必须使用时间复杂度为 O(log n) 的算法。约束:1 ≤ nums.length ≤ 10^4;-10^4 ≤ nums[i], target ≤ 10^4;nums 为无重复元素的升序排列数组。

核心要点

  • 找「第一个 ≥ target 的位置」(标准解) :这正是插入位置的定义。
  • 半开区间模板 :用 l 、 r 表示 [l, r) ,循环条件 l &lt; r ,收缩写 r = mid (保留 mid)或 l = mid + 1 。
  • 为什么用半开区间 :插入位置可能是 n (target 大于所有元素),半开区间的右边界天然支持这一点。
  • 结束状态 : l == r 即为答案。

常见陷阱

  • 右边界写成 len(nums) − 1 :会导致 target 大于所有元素时返回 n − 1 而非 n 。必须用半开区间。
  • 收缩写成 r = mid − 1 :会排除可能的答案。找「第一个 ≥ target」时必须用 r = mid 。
  • 循环条件写成 l &lt;= r :半开区间模板必须用 l &lt; r 。
  • 用 bisect_left(nums, target) :这是 Python 的标准库答案,一行搞定且正确;面试中应先手写模板再提这个。

参考实现

class Solution:
    def searchInsert(self, nums: list[int], target: int) -> int:
        l, r = 0, len(nums)          # 半开区间 [l, r),r 可以是 n
        while l < r:
            mid = (l + r) // 2
            if nums[mid] < target:
                l = mid + 1          # mid 不可能是答案
            else:
                r = mid              # mid 可能是答案,保留
        return l