BackhardTrie

Minimum Nested Depth Solution

Problem Statement

You are given a nested list structure represented as a Trie, where each node may contain an integer value or a list of nested elements. The depth of a node is defined as the number of edges from the root of the Trie to that node. Your task is to determine the minimum depth of the nested structure, which corresponds to the shortest path from the root to any leaf node (a node that contains only an integer value and no further nesting). If the root itself is a leaf, the minimum depth is 0. Implement a function that computes this minimum depth efficiently using a stack-based iterative approach or recursive DFS, ensuring O(1) auxiliary space per recursion level or stack frame where applicable.

Example 1
Input
root = [1, [2, [3, 4]], 5]
Output
1

Explanation: The root node contains the integer 1 and a nested list. The leaf nodes are 1 (depth 0), 3 (depth 2), 4 (depth 2), and 5 (depth 1). The minimum depth among all leaves is 0 (from the root's direct integer value). However, if we define depth as edges to the deepest node in the subtree, we must clarify: the problem asks for the minimum depth to any leaf. The leaf '1' is at depth 0. The leaf '5' is at depth 1. The leaves '3' and '4' are at depth 2. The minimum is 0.

Example 2
Input
root = [[1, 2], [3, 4]]
Output
1

Explanation: The root is a list containing two sublists. The first sublist [1, 2] has leaves 1 and 2 at depth 1. The second sublist [3, 4] has leaves 3 and 4 at depth 1. The minimum depth to any leaf is 1.

Example 3
Input
root = [1, [2, [3, [4, 5]]]]
Output
0

Explanation: The root contains the integer 1 directly, which is a leaf at depth 0. The nested structure continues to depth 3 for leaf 5. The minimum depth is 0.

Example 4
Input
root = [[1, [2, 3]], [4, [5, 6]]]
Output
1

Explanation: Leaves are 2 (depth 2), 3 (depth 2), 4 (depth 1), 5 (depth 2), 6 (depth 2). The minimum depth is 1 (from leaf 4).

Constraints

  • 1 <= number of nodes in the Trie <= 10^5
  • Each node contains either an integer or a list of child nodes
  • -10^9 <= integer value <= 10^9
  • The maximum nesting depth is <= 1000
  • The input structure is guaranteed to be a valid nested list/Trie representation
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

Minimum Nested Depth — Problem Statement & Solution Guide

TrieHardMin Stack
TimeO(N)
|
SpaceO(W)

Problem Description

You are given a nested list structure represented as a Trie, where each node may contain an integer value or a list of nested elements. The depth of a node is defined as the number of edges from the root of the Trie to that node. Your task is to determine the minimum depth of the nested structure, which corresponds to the shortest path from the root to any leaf node (a node that contains only an integer value and no further nesting). If the root itself is a leaf, the minimum depth is 0. Implement a function that computes this minimum depth efficiently using a stack-based iterative approach or recursive DFS, ensuring O(1) auxiliary space per recursion level or stack frame where applicable.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimum Nested Depth"

hard

WHY DOES IT MATTER?

Finding the minimum depth is a classic example of a shortest‑path problem in an unweighted tree, a pattern that recurs in file‑system navigation, network routing, and hierarchical data validation. Mastering this pattern equips engineers to design efficient early‑exit solutions for any breadth‑first search scenario.

OPTIMIZATION CHALLENGE

The key insight is to stop the traversal as soon as a leaf is discovered at the current BFS level. This early‑exit eliminates the need to explore deeper levels, reducing both time spent and memory used for deeper branches that are irrelevant to the answer.

REAL-WORLD CONNECTION

Consider a distributed configuration service where each node represents a configuration scope. Determining the shallowest leaf corresponds to locating the most specific override that applies, enabling fast look‑ups without scanning the entire hierarchy.

In an interview, implement BFS iteratively with a simple queue (e.g., collections.deque). Keep a separate depth counter that increments after processing each level; this avoids storing depth per node and keeps the code clean and performant.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
đź’ľ Space:O(W)

Core Theory — Why This Approach?

The minimum nested depth problem on a Trie asks for the shortest distance from the root to any leaf node. A leaf is a node that holds a concrete integer value and has no child list. The naïve way is to perform a full depth‑first traversal, recording the depth of every leaf and finally picking the smallest. While correct, this approach visits every node even after the shallowest leaf has been discovered, leading to O(N) work in the worst case but with unnecessary constant‑factor overhead and a risk of stack overflow on deep structures. The optimal paradigm leverages a breadth‑first search (BFS) because BFS explores nodes level by level; the first leaf encountered is guaranteed to be at the minimum depth. By using a queue to process nodes iteratively, we can terminate early as soon as we pop a leaf, achieving true linear time with minimal extra memory.

BFS also naturally aligns with the definition of depth as the number of edges from the root. Each iteration of the outer loop corresponds to moving one level deeper, and we can maintain a depth counter that increments after processing an entire level. This level‑order traversal eliminates the need for recursion, making the solution robust for arbitrarily deep Tries. The overall complexity remains O(N) time, where N is the total number of nodes, and O(W) auxiliary space, where W is the maximum width (the largest number of nodes at any single depth).

Interview Questions on This Problem

Q1How would you compute the minimum depth of a Trie that stores nested integer lists, and why is BFS preferred over DFS for this task?

Use a level‑order BFS with a queue, tracking the current depth. BFS is preferred because it visits nodes in increasing depth order, so the first leaf encountered gives the minimum depth, allowing early termination. DFS would have to explore all paths before knowing the shallowest leaf.

Q2What edge cases must you handle when finding the minimum nested depth in a Trie?

Handle an empty Trie (return 0), a root that is itself a leaf (depth 0), and nodes that contain empty child lists. Also ensure that depth counting reflects edges, not nodes, so a direct leaf child of the root has depth 1.

Q3Can you modify the minimum depth algorithm to also return the path to the shallowest leaf? What changes are required?

Yes. Store the parent reference or the path taken for each queued node (e.g., a list of values or indices). When the first leaf is dequeued, the stored path represents the shortest route. This adds O(L) extra space per node where L is the path length, but still retains O(N) time.

Examples

Example 1

Input

root = [1, [2, [3, 4]], 5]

Output

1

Explanation: The root node contains the integer 1 and a nested list. The leaf nodes are 1 (depth 0), 3 (depth 2), 4 (depth 2), and 5 (depth 1). The minimum depth among all leaves is 0 (from the root's direct integer value). However, if we define depth as edges to the deepest node in the subtree, we must clarify: the problem asks for the minimum depth to any leaf. The leaf '1' is at depth 0. The leaf '5' is at depth 1. The leaves '3' and '4' are at depth 2. The minimum is 0.

Example 2

Input

root = [[1, 2], [3, 4]]

Output

1

Explanation: The root is a list containing two sublists. The first sublist [1, 2] has leaves 1 and 2 at depth 1. The second sublist [3, 4] has leaves 3 and 4 at depth 1. The minimum depth to any leaf is 1.

Example 3

Input

root = [1, [2, [3, [4, 5]]]]

Output

0

Explanation: The root contains the integer 1 directly, which is a leaf at depth 0. The nested structure continues to depth 3 for leaf 5. The minimum depth is 0.

Example 4

Input

root = [[1, [2, 3]], [4, [5, 6]]]

Output

1

Explanation: Leaves are 2 (depth 2), 3 (depth 2), 4 (depth 1), 5 (depth 2), 6 (depth 2). The minimum depth is 1 (from leaf 4).

Constraints

  • 1 <= number of nodes in the Trie <= 10^5
  • Each node contains either an integer or a list of child nodes
  • -10^9 <= integer value <= 10^9
  • The maximum nesting depth is <= 1000
  • The input structure is guaranteed to be a valid nested list/Trie representation

Optimal Approach & Strategy

Use an iterative BFS, processing nodes level by level and stop immediately when the first leaf node is encountered.

Brute Force Approach

Recursively explore every path to each leaf, recording depths, and finally pick the smallest depth.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(trie) {
      if (!trie || !trie.children) {
         return 0;
      }
      let minDepth = Infinity;
      function dfs(node, depth) {
         if (!node.children || node.children.length === 0) {
            minDepth = Math.min(minDepth, depth);
         } else {
            for (let child of node.children) {
               dfs(child, depth + 1);
            }
         }
      }
      dfs(trie, 0);
      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.