↓Skip to main content
  1. LeetCode/

LeetCode 35: Search Insert Position

·2 mins· ·
LeetCode Easy Array Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-05-11

  • Submissions: Wrong Answer → Accepted → Runtime Error ×2 → Accepted → Wrong Answer → Time Limit Exceeded → Wrong Answer ×2 → Runtime Error → Accepted ×2

Approach
#

The insert position is the first index with a value >= target, i.e. the lower bound (Binary Search Template 1). With a half-open [l, r): if nums[mid] < target the answer is to the right, l = mid + 1; otherwise mid may be the answer, r = mid.

My Attempts
#

This took 12 submissions, mostly from mixing interval styles:

  • At first it lacked a return value and computed mid with / (TypeError).
  • A November 2022 rewrite used a half-open right = len(nums) but wrote right = mid - 1, skipping a possible answer: [0, 7], target = 5 should be 1; it returned 0.

Solution
#

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        l, r = 0, len(nums)
        while l < r:
            mid = (l + r) // 2
            if nums[mid] < target:
                l = mid + 1
            else:
                r = mid
        return l

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • Do not mix interval styles: a half-open r = len(nums) goes with while l < r and r = mid.

Interview Explanation
#

The answer is the first position not less than the target, so I run a half-open lower bound: go right when the middle is smaller, otherwise shrink the right bound to the middle. The final l is the answer. Time O(log n).

Related

LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written
LeetCode 66: Plus One
·2 mins
LeetCode Easy Array Math
LeetCode 66 note: add one from the last digit, turning 9s into 0s while carrying, and prepend 1 when every digit was 9
LeetCode 26: Remove Duplicates from Sorted Array
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 26 note: overwrite in place with a write pointer for the next slot, writing only values different from the last one written
LeetCode 14: Longest Common Prefix
·2 mins
LeetCode Easy Array String Trie
LeetCode 14 note: bound by the shortest string and check each position across all strings; the first mismatch gives the answer’s length
LeetCode 1: Two Sum
·2 mins
LeetCode Easy Array Hash-Table
LeetCode 1 note: store seen numbers in a hash map while scanning and look up target - x; checking before storing prevents using one element twice
LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found