Below is a pragmatic way to “fish-out’’ recurring pieces of structure in a directed-acyclic graph while staying almost strictly linear in the size of the graph.
The key idea is to
- scan the DAG once in topological order,
- assign every vertex a compact structural fingerprint that summarizes the
sub-DAG hanging under it, and
- keep a hash-table ⟶ counter so we immediately know which fingerprints
occur more than once.
Because fingerprinting is done with a constant number k of iterations and all
operations per iteration are O(out-degree), the total running time is
O(k · (V+E)) — linear for any fixed k (typically k=2…5 already works
surprisingly well).
Why this is only “best-effort”
• Finding every repeated subgraph exactly is NP-hard (general subgraph
isomorphism).
• Hash-based fingerprints can collide (two non-isomorphic sub-DAGs might get
the same 64-bit hash), but with a good hash function the probability is
negligible.
• We only find rooted repeated pieces: two subgraphs are considered equal
if there is an isomorphism that maps the two roots to each other and
preserves edge direction/labels.
In practice that captures most “motifs’’ people care about
(re-occurring expressions, repeated circuits, duplicated code blocks …).
The algorithm
Notation
G = (V, E) — a DAG (possibly vertex/edge-labelled)
base(u) — label/type of vertex u (or a constant 0 if you do not care)
h₀(u) — initial hash = hash(base(u))
k — number of refinement rounds (constant)
Algorithm (pseudo-Python)
from collections import defaultdict
import hashlib, struct, itertools
def multiset_hash(values):
"""Order-independent hash of a multiset (sum of 64-bit hashes mod 2⁶⁴)."""
h = 0
for v in values:
h = (h + v) & 0xFFFFFFFFFFFFFFFF
return h
def dag_fingerprint_patterns(G, k=3):
V, E = G # assume G gives you V and adjacency list adj[u]
order = topo_sort(G) # O(V+E)
# step 1: initial hashes
h = {u: hash64(base(u)) for u in V}
# step 2: k rounds of Weisfeiler–Lehman like refinement
for _ in range(k):
for u in reversed(order): # bottom-up
child_hashes = [h[v] for v in G.adj[u]] # out-neighbors
h_new = hash64( (h[u], multiset_hash(child_hashes)) )
h[u] = h_new
# step 3: collect duplicates
bucket = defaultdict(list)
for u, sig in h.items():
bucket[sig].append(u)
# Patterns = buckets with more than one representative
patterns = {sig: occ for sig, occ in bucket.items() if len(occ) > 1}
return patterns # dict: fingerprint -> [list of root vertices]
hash64 can be (for instance) the first 64 bits of SHA-256 of the byte
representation of the tuple.
What does “pattern’’ actually contain?
Each entry patterns[sig] tells you
• the set of root vertices whose k-radius surrounding sub-DAGs are
isomorphic;
• the size of the list = how many times it appears.
If you need the concrete subgraph, just
for root in patterns[some_sig]:
extract all vertices reachable from root within distance ≤ k
Choosing k
k = 1 only distinguishes by (label, multiset of immediate children)
k = 2 also compares grandchildren → catches 90 % of “duplicated code’’
k = 3-4 rarely misses anything visualisable by eye, yet still linear.
Accuracy vs. speed knobs
• Increase k → fewer false positives, slightly slower (linear in k).
• Use a stronger hash (128 bit) if collisions worry you.
• Limit search to vertices whose out-degree ≤ d if you want a yet faster
heuristic (skip high-fan-out hubs).
Extensions / variations
-
Edge-labels
Mix the label into the hash of every child: hash64( (edge_label, h[child]) )
-
Size threshold
Keep track of the number of descendants during hashing; discard patterns
smaller than s.
-
Frequent paths instead of general sub-DAGs
Replace the multiset_hash by an ordered tuple hash – you will then only
detect repeated directed paths.
-
Min-hash sampling
When the graph is huge (|E| > 10⁸) you can hash only a random subset of
children per vertex to get a constant-time per vertex algorithm.
Complexity recap
topological sort O(V+E)
k hashing rounds O(k · (V+E))
hashtable bookkeeping O(V)
Total O((k+1)(V+E)) ≈ linear
Memory:
one 64-bit integer per vertex (+ hash table overhead) ≈ O(V).
Tiny worked example
Suppose the DAG represents arithmetic expressions:
(*) (*) two identical
/ \ / \ multiplications
(+) c (+) c
/ \ / \
a b x y
After 2 refinement rounds both ‘*’ nodes receive the same fingerprint,
landing in the same bucket with count = 2.
patterns looks like:
fingerprint 0x4a38fc... : [v₁, v₇] # v₁ and v₇ are the roots of the two *
Bottom line
• Exact “find every repeated subgraph’’ is impossible in linear time.
• A WL-style structural hashing pass gives you an extremely fast,
memory-friendly, and surprisingly accurate detector of repeated motifs.
• You can start using the 30-line routine above today, and later dial
k / hash width / sampling strategy until it matches your needs and hardware
budget.