Skip to content

Binary insertion with `bisect_right` [ref]

Problem

  • Find the insertion index after existing 3 values in [1, 3, 3, 5].
  • Compare left and right insertion indices of 3 in [1, 3, 3, 5].
  • Replace the first value greater than 3 in [1, 3, 5] with 3.

Python solution

import bisect

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

(bisect.bisect_left(nums, 3), bisect.bisect_right(nums, 3))
# (1, 3)

tails = [1, 3, 5]
i = bisect.bisect_right(tails, 3)
tails[i] = 3
tails  # [1, 3, 3]