Find a Word Spanning the Fragments at a Tree's Leaves
Trees & GraphsAuto-graded · 18 test casesLast updated
Stream the leaf strings of a binary tree in left-to-right order and decide whether a pattern occurs in their concatenation, without ever building the full text.
Pattern in the Leaf Fragments
A binary tree stores text only in its leaves. Each node is a dictionary with the keys "val", "left" and "right". A node is a leaf when both "left" and "right" are None. A leaf's "val" holds a string of lowercase letters. For an internal node, "val" is irrelevant: it may be empty, None, or missing, and it must be ignored.
Read the leaves from left to right and join their strings in that order to form one long string T. Given a non-empty string pattern, decide whether pattern occurs in T as a contiguous substring. An occurrence may begin in one leaf and finish in a later one, possibly crossing many leaves.
T can be very large, so do not build it. Process the leaf characters as a stream, using auxiliary memory of O(len(pattern) + height).
Input
root: the root node dictionary of the tree, orNonefor an empty tree.pattern: the non-empty string to look for.
Output
Return True if pattern is a substring of T, otherwise False. If root is None, return False.
Notes
- A leaf whose
"val"is"",Noneor missing contributes no characters. - A tree consisting of a single node is a leaf, so its own string is
T. - If
patternis longer thanT, the answer isFalse.
Constraints
- The tree has between
1and10^5nodes. - The total number of characters across all leaves is at most
10^7. 1 <= len(pattern) <= 10^5.- All leaf strings and
patternuse only lowercase English letters. - Extra space must be
O(len(pattern) + H), whereHis the tree height.
Examples
Example 1
Input: find_pattern_in_leaves({'val': '', 'left': {'val': '', 'left': {'val': 'ab', 'left': None, 'right': None}, 'right': {'val': 'cd', 'left': None, 'right': None}}, 'right': {'val': 'xyz', 'left': None, 'right': None}}, 'bcdx')
Output: True
Example 2
Input: find_pattern_in_leaves({'val': '', 'left': {'val': 'hello', 'left': None, 'right': None}, 'right': {'val': 'world', 'left': None, 'right': None}}, 'word')
Output: False
Hints
Hint 1
Never concatenate the leaves. Think of the leaf characters as a stream arriving one at a time, and ask what small amount of state you must remember between characters.
Hint 2
Use the KMP failure (prefix) table of the pattern. Keep a single integer: how many characters of the pattern the stream currently ends with. A leaf boundary is just the next character, so this integer simply carries over.
Hint 3
Traverse iteratively with an explicit stack, pushing the right child before the left so that leaves pop in left-to-right order. This avoids recursion limits on deep trees and keeps the stack at O(height).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the leaf texts, read left to right, as a character stream and run the Knuth-Morris-Pratt matcher over it. The full string T is never built.
- Order the leaves. Do a depth-first traversal with an explicit stack. For an internal node, push the right child and then the left child, so the left child is popped first. This yields leaves in strict left-to-right order. Internal nodes contribute no characters.
- Build the failure table. For each position
iof the pattern,fail[i]is the length of the longest proper prefix ofpattern[0..i]that is also a suffix of it. - Match on the stream. Keep one integer
k, the length of the longest prefix ofpatternthat is a suffix of the characters seen so far. For each incoming characterch:- While
k > 0andch != pattern[k], setk = fail[k - 1]. - If
ch == pattern[k], incrementk. - If
k == len(pattern), returnTrue.
- While
- If the stream ends without a full match, return
False.
Why it is correct
- Visiting the left subtree before the right produces exactly the characters of
Tin order. - After each character,
kequals the length of the longest pattern prefix that is a suffix of the text read so far. On a mismatch, the failure table gives the next-longest candidate, so no alignment is skipped. On a match, the candidate grows by one. k == len(pattern)therefore happens exactly when the pattern ends at the current character.kis kept outside the per-leaf loop, so leaf boundaries are invisible. Matches spanning many leaves are found, and empty leaves leavekunchanged.- Self-overlapping patterns (for example
"aab"in"aaab") are handled by the fallback, which a naive reset to 0 would miss.
Complexity
- Time:
O(m + N + L)for pattern lengthm,Nnodes andLtotal leaf characters. The fallback loop is amortized, sincekgrows by at most one per character and each fallback strictly lowers it. - Space:
O(m + H). The failure table usesmintegers, and the stack holds at most one pending right sibling per level plus the current node.
Reference solution
from typing import Dict, Optional
def find_pattern_in_leaves(root: Optional[Dict], pattern: str) -> bool:
if root is None:
return False
m = len(pattern)
# KMP failure table: fail[i] = length of the longest proper prefix of
# pattern[0..i] that is also a suffix of it.
fail = [0] * m
k = 0
for i in range(1, m):
while k and pattern[i] != pattern[k]:
k = fail[k - 1]
if pattern[i] == pattern[k]:
k += 1
fail[i] = k
# Iterative DFS, right pushed first so left is processed first.
stack = [root]
k = 0
while stack:
node = stack.pop()
left = node.get("left")
right = node.get("right")
if left is None and right is None:
for ch in node.get("val", "") or "":
while k and ch != pattern[k]:
k = fail[k - 1]
if ch == pattern[k]:
k += 1
if k == m:
return True
else:
if right is not None:
stack.append(right)
if left is not None:
stack.append(left)
return False