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

Basics: floor and ceiling with bisect

easy basics ~10 min

Implement class SortedSet on top of a plain Python list kept in sorted order, using the bisect module:

  • SortedSet() starts empty.
  • add(x) inserts the integer x. Adding a value that's already there does nothing (it's a set).
  • floor(x) returns the largest stored value <= x, or None if there isn't one.
  • ceiling(x) returns the smallest stored value >= x, or None if there isn't one.
  • __len__() returns how many distinct 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

Values may be negative. floor and ceiling must use binary search (O(log n)); the tests make 100,000 queries on a set of 50,000 values. bisect.insort is fine for add.

Show hint

i = bisect_right(a, x) counts the values <= x, so the floor is a[i - 1] when i > 0; j = bisect_left(a, x) counts the values < x, so the ceiling is a[j] when j < len(a).

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