Skip to content

Binary insertion with `bisect_left` [ref]

Problem

  • Find the first insertion index for 3 in [1, 3, 3, 5].
  • Insert 3 there while keeping that list sorted.
  • Find insertion indices for 0, 4, and 9 in [1, 3, 5, 7].
  • Replace the first value at least 4 in [2, 5, 8] with 4.

Python solution

import bisect

nums = [1, 3, 3, 5]
i = bisect.bisect_left(nums, 3)
i  # 1

nums.insert(i, 3)
nums  # [1, 3, 3, 3, 5]

nums = [1, 3, 5, 7]
[bisect.bisect_left(nums, x) for x in (0, 4, 9)]  # [0, 2, 4]

nums = [2, 5, 8]
i = bisect.bisect_left(nums, 4)
nums[i] = 4
nums  # [2, 4, 8]