BackhardTrie

Minimal Layer Depth Solution

Problem Statement

Given a trie data structure, design an algorithm to find the minimum depth of the trie. The minimum depth is defined as the minimum number of layers from the root to a leaf node. A leaf node is a node with no children.

Example 1
Input
{"root":{"a":{"b":{"c":{}}}}}
Output
3

Explanation: Step-by-step: with input X, we do A then B then C, giving output Y. The minimum depth of the Trie is the minimum number of layers from the root to a leaf node. In this case, the path from root to leaf is root -> a -> b -> c -> {}.

Example 2
Input
{"root":{"a":{"b":{}}}}
Output
2

Explanation: Step-by-step: with input X, we do A then B, giving output Y. The minimum depth of the Trie is the minimum number of layers from the root to a leaf node. In this case, the path from root to leaf is root -> a -> b -> {}.

Constraints

  • The input will contain at least one node and at most 10^5 nodes
  • Each node value is unique and ranges from 1 to 10^6
  • The input guarantees at least one leaf node
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Minimal Layer Depth — Problem Statement & Solution Guide

TrieHardMin Stack
TimeO(N)
|
SpaceO(H)

Problem Description

Given a trie data structure, design an algorithm to find the minimum depth of the trie. The minimum depth is defined as the minimum number of layers from the root to a leaf node. A leaf node is a node with no children.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimal Layer Depth"

hard

WHY DOES IT MATTER?

Finding the minimum depth of a trie is a classic example of shortest‑path search in an unweighted tree, a pattern that recurs in many interview problems such as minimum depth of binary trees, level order traversal, and early exit BFS scenarios. Mastery of this pattern demonstrates a candidate's ability to reason about tree structures, termination conditions, and optimal traversal strategies.

OPTIMIZATION CHALLENGE

The key insight is that the first leaf encountered in a level‑order (BFS) walk is guaranteed to be at the minimal depth, allowing the algorithm to stop immediately without scanning the entire tree. This early‑exit property reduces the worst‑case time from O(N × L) to O(N) and eliminates unnecessary recursion depth.

REAL-WORLD CONNECTION

In distributed key‑value stores like DynamoDB or Cassandra, data is often sharded using prefix trees. Determining the shallowest leaf corresponds to locating the least specific key range, which helps in load balancing and in designing efficient range queries across nodes.

When coding the solution, use an explicit queue (or deque) to store pairs of (node, depth). Push the root with depth 1, then loop: pop, check for leaf, return depth if leaf, otherwise enqueue all non‑null children with depth+1. This pattern avoids hidden recursion stack overflow on deep tries and makes the early‑exit condition crystal clear.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(H)

Core Theory — Why This Approach?

A trie (prefix tree) stores strings in a hierarchical manner where each edge represents a character and each node aggregates the prefixes seen so far. The minimum depth of a trie is the length of the shortest root‑to‑leaf path, i.e., the fewest layers needed to reach a node that has no children. A naïve solution might scan every possible path without pruning, leading to O(N × L) time where N is the number of inserted strings and L is the average string length, because each recursive call could revisit the same subtree multiple times. This quickly becomes infeasible for large dictionaries (hundreds of thousands of words) as the total node count can approach the sum of all characters across all strings. The optimal paradigm leverages a single breadth‑first search (BFS) or depth‑first search (DFS) that visits each node exactly once, stopping as soon as the first leaf is encountered. BFS naturally yields the shortest path in an unweighted tree because it explores nodes level by level, guaranteeing that the first leaf discovered resides at the minimal depth. DFS can also achieve O(N) time if it carries the current depth and returns early when a leaf at a shallower depth is found, but BFS is conceptually simpler for the minimum‑depth problem.

Interview Questions on This Problem

Q1How would you compute the minimum depth of a trie that stores millions of URLs for a web crawler, and why is BFS preferred over DFS in this scenario?

Use a BFS queue starting from the root, tracking the depth of each node. Dequeue nodes level by level; the moment you encounter a node with no children (a leaf), return its depth. BFS is preferred because it guarantees the first leaf found is at the smallest possible depth, eliminating the need to explore deeper branches and thus reducing runtime on massive trees.

Q2In a fintech platform, you need to validate that a newly added transaction code does not create a shallow leaf that could be exploited. How can you maintain the minimum depth efficiently after each insertion?

Maintain a global variable minDepth. When inserting a new code, traverse the path; if you create a new leaf, compare its depth with minDepth and update if smaller. If an existing leaf becomes an internal node, recompute minDepth by performing a BFS from the root, which is still O(N) but amortized over many insertions becomes acceptable because updates are infrequent.

Q3A startup wants to compress a large dictionary by pruning all branches deeper than the minimum depth of the trie. Describe an algorithm to find that depth and then prune the tree.

First run a BFS to locate the minimum depth as described. Then perform a second DFS/BFS that stops expanding any node whose depth exceeds the found minimum; those subtrees are discarded. This two‑pass approach runs in O(N) time and uses O(H) auxiliary space, where H is the height of the trie.

Examples

Example 1

Input

{"root":{"a":{"b":{"c":{}}}}}

Output

3

Explanation: Step-by-step: with input X, we do A then B then C, giving output Y. The minimum depth of the Trie is the minimum number of layers from the root to a leaf node. In this case, the path from root to leaf is root -> a -> b -> c -> {}.

Example 2

Input

{"root":{"a":{"b":{}}}}

Output

2

Explanation: Step-by-step: with input X, we do A then B, giving output Y. The minimum depth of the Trie is the minimum number of layers from the root to a leaf node. In this case, the path from root to leaf is root -> a -> b -> {}.

Constraints

  • The input will contain at least one node and at most 10^5 nodes
  • Each node value is unique and ranges from 1 to 10^6
  • The input guarantees at least one leaf node

Optimal Approach & Strategy

Perform a single BFS from the root, tracking depth; return the depth of the first leaf encountered, achieving O(N) time with early exit.

Brute Force Approach

Recursively explore every root‑to‑leaf path, compute each path length, and keep the smallest; this visits each node many times and runs in O(N × L).

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(root) {
   if (!root) return 0;
   let queue = [[root, 1]];
   let minDepth = Infinity;
   while (queue.length) {
       let [node, depth] = queue.shift();
       if (!node.children) {
           minDepth = Math.min(minDepth, depth);
       }
       for (let child in node.children) {
           queue.push([node.children[child], depth + 1]);
       }
   }
   return minDepth;
}

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.