13/35
Part 4 of 7 · Walking alongsideLearn

The trie's real edge over a set: you can walk it one letter at a time and stop the moment no word goes on. Any search that reads text letter by letter can carry a trie node along.

Word Break, on Netflix's LeetCode company tag list (1 source), is the cleanest case: can text be cut into a sequence of dictionary words?

# words is a set
def can_split_slices(text, words):
    # ok[i]: text[:i] splits into words
    ok = [True] + [False] * len(text)
    for end in range(1, len(text) + 1):
        for start in range(end):
            if ok[start] and text[start:end] in words:
                ok[end] = True
                break
    return ok[-1]


GEAR = ["tent", "tents", "pole", "poles", "stake", "take", "takes"]
print(can_split_slices("tentspole", set(GEAR)), can_split_slices("tentpol", set(GEAR)))
True False

The usual answer is a table. ok[i] is True when text[:i] splits into words. ok[0] is True for the empty split. ok[end] becomes True when some start has ok[start] and text[start:end] is in the word set.

Predict

can_split_slices on a text of 1,000 letters, at worst: about how many slices does it try?

Pick an answer above to see the rest