Two colours: bipartite graphs
A graph is bipartite if its nodes can be divided into two groups with no edges inside each group (for example, people and jobs). It is checked by colouring with a traversal: each neighbour gets the opposite colour; if one already has the same colour as the current node, it is not bipartite. It is equivalent to having no odd-length cycles.
Prefix trees: tries
A trie stores words letter by letter: each node is a dictionary whose keys are the next letters. Words with the same prefix share a path, so looking for “all those starting with ca” costs the length of the prefix, not the number of words.
from collections import deque
def is_bipartite(n, edges):
neighbors = [[] for _ in range(n)]
for a, b in edges:
neighbors[a].append(b)
neighbors[b].append(a)
color = [-1] * n
for start in range(n):
if color[start] != -1:
continue
color[start] = 0
queue = deque([start])
while queue:
u = queue.popleft()
for v in neighbors[u]:
if color[v] == -1:
color[v] = 1 - color[u] # the neighbor gets the other color
queue.append(v)
elif color[v] == color[u]:
return False
return True
print(is_bipartite(4, [(0, 1), (1, 2), (2, 3), (3, 0)])) # True (even cycle)
print(is_bipartite(3, [(0, 1), (1, 2), (2, 0)])) # False (odd cycle)
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for letter in word:
node = node.setdefault(letter, {})
node["$"] = True
def starts_with(self, prefix):
node = self.root
for letter in prefix:
if letter not in node:
return False
node = node[letter]
return True
t = Trie()
for p in ("casa", "casco", "cama"):
t.insert(p)
print(t.starts_with("cas"), t.starts_with("cu")) # True False
- A special node (here
"$") marks where a word ends:casis a prefix ofcasa, but it is not a stored word. - To list the words with a prefix, go down to its node and walk the whole subtree in alphabetical order.
- It is used in autocompletion, spell checkers and routing tables.
You practice it in Is it bipartite? and Autocomplete with a trie.