progress

~/problems / Binary search / Sorted containers (bisect)

Floor and ceiling with bisect

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Implement class SortedSet on a plain Python list kept sorted with the bisect module:

  • add(x): insert x (no duplicates).
  • floor(x): the largest stored value <= x, or None.
  • ceiling(x): the smallest stored value >= x, or None.
  • __len__(): how many values are stored.
s = SortedSet()
for v in [10, 3, 7, 3]:
    s.add(v)
len(s)          # 3       (stored: [3, 7, 10])
s.floor(8)      # 7
s.ceiling(8)    # 10
s.floor(7)      # 7       (equal counts)
s.floor(2)      # None    (nothing is <= 2)
s.ceiling(11)   # None

bisect.insort is fine for add. ⭐ Bonus: a speed test earns a star if floor and ceiling binary search (O(log n)).

Show hint

bisect_right(a, x) counts values <= x; bisect_left(a, x) counts values < x.

Topic: Sorted containers (bisect). Ordered-set operations in Python: bisect.insort, floor/ceiling lookups.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc