29/35
Part 7 of 7 · Follow-upsLearn

For a fixed word list and prefix questions only, a sorted list or a set of prefixes can beat a trie

Two simpler structures answer prefix questions:

from bisect import bisect_left

ordered = sorted(CATALOG)
prefixes = {word[:i] for word in CATALOG for i in range(1, len(word) + 1)}


def has_prefix_bisect(p):
    # where p would go: every word from here on is >= p
    i = bisect_left(ordered, p)
    return i < len(ordered) and ordered[i].startswith(p)


def count_prefix_bisect(p):
    return bisect_left(ordered, p + "{") - bisect_left(ordered, p)


print(ordered)
print(has_prefix_bisect("te"), count_prefix_bisect("te"), count_prefix_bisect("x"))
print(len(prefixes), "te" in prefixes)
Predict

ordered is ['lamp', 'lantern', 'tarp', 'tea', 'tent', 'tents']. What is bisect_left(ordered, "te")?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

Which answers "is this a prefix?" fastest: the trie, the sorted list or the set of every prefix?

Pick an answer above to see the rest
Predict

Sorted, the items read lamp, lantern, tarp, tea, tent, tents. What is lantern's shortest unique prefix?