KatInterview

Find a Word Spanning the Fragments at a Tree's Leaves

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsbinary-treekmpstring-matching

Last 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, or None for 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 "", None or missing contributes no characters.
  • A tree consisting of a single node is a leaf, so its own string is T.
  • If pattern is longer than T, the answer is False.

Constraints

  • The tree has between 1 and 10^5 nodes.
  • The total number of characters across all leaves is at most 10^7.
  • 1 <= len(pattern) <= 10^5.
  • All leaf strings and pattern use only lowercase English letters.
  • Extra space must be O(len(pattern) + H), where H is 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).