Magicsheet logo

Smallest String Starting From Leaf

Medium
12.5%
Updated 8/1/2025

Smallest String Starting From Leaf

What is this problem about?

The "Smallest String Starting From Leaf" interview question involves traversing a binary tree where each node contains a value from 0 to 25, representing characters 'a' through 'z'. You need to find the lexicographically smallest string that starts from a leaf node and ends at the root. This "Smallest String Starting From Leaf coding problem" is a unique twist on tree paths, as the strings are constructed in reverse order of the typical root-to-leaf traversal.

Why is this asked in interviews?

Amazon and Google ask this to test your tree traversal (DFS) skills and your ability to compare strings. It requires careful handling of string construction and lexicographical comparison. It evaluates if you can identify that a simple greedy choice at each node (picking the smaller child) doesn't always lead to the globally smallest string, as the strings are compared after they are fully formed.

Algorithmic pattern used

This follows the "Depth-First Search (DFS) and String interview pattern".

  1. Perform a DFS traversal of the tree.
  2. As you go down, keep track of the path from the root.
  3. When you reach a leaf node:
    • Construct the string by reversing the current path.
    • Compare this string with the "best" string found so far and update it if the current one is smaller.
  4. Return the best string.

Example explanation

Tree: Root 'z' (25), Left 'b' (1), Right 'a' (0). Leaf nodes: 'b' and 'a'.

  1. Path 1: Root to leaf 'b'. String: "bz" (reversed is "zb").
  2. Path 2: Root to leaf 'a'. String: "az" (reversed is "za").
  3. "za" is lexicographically smaller than "zb". Result: "za". If there were further nodes, say 'a' had a child 'c', the path would be "acz" -> "zca".

Common mistakes candidates make

A common error is trying to pick the smallest child at each step (Greedy). This fails because a larger character near the leaf can be better if it's followed by much smaller characters closer to the root. Another mistake is not correctly handling the string reversal or the comparison of strings of different lengths (e.g., "ab" vs "abab").

Interview preparation tip

In tree path problems, if you need the "best" path, you usually have to explore all leaf nodes. Don't be fooled by greedy options unless the problem specifically allows it. This "Smallest String Starting From Leaf interview question" is a great reminder to trust full traversal for path-based optimizations.

Similar Questions