Magicsheet logo

Path Sum IV

Medium
100%
Updated 6/1/2025

Path Sum IV

What is this problem about?

The Path Sum IV problem encodes a binary tree as a flat array where each element represents a node as a 3-digit number: the first digit is the level, the second is the position within that level, and the third is the value. Find the sum of all root-to-leaf path sums. This coding problem decodes a compact tree representation using a hash map. The array, hash table, DFS, binary tree, and tree interview pattern is the core.

Why is this asked in interviews?

Alibaba and TikTok ask this because it tests encoding/decoding of tree structures — a skill relevant to serialization, database storage, and compressed data formats. The ability to reconstruct tree relationships from an encoded format demonstrates strong data structure reasoning.

Algorithmic pattern used

Hash map reconstruction + DFS. Decode each 3-digit number: level = num // 100, pos = (num % 100) // 10, val = num % 10. Store in map[(level, pos)] = val. DFS from root (1, 1): pass the current running sum. At each node, check if children (level+1, 2*pos-1) and (level+1, 2*pos) exist. If a node has no children (leaf), add the running sum to total.

Example explanation

nums=[113,215,221]. Decode: (1,1,3),(2,1,5),(2,2,1). Tree: root=3 at level 1. Children: 5 at (2,1), 1 at (2,2). Path 3→5: sum=8. Path 3→1: sum=4. Total = 12.

Common mistakes candidates make

  • Incorrect position calculation for children: left child = (level+1, 2*pos-1), right = (level+1, 2*pos).
  • Not identifying leaf nodes correctly (no children in the map).
  • Off-by-one in position encoding.
  • Not passing running sum correctly through DFS.

Interview preparation tip

Compact tree encodings appear in competitive programming and data engineering. Practice decoding tree structures from various formats: array-of-3-digit-codes, BFS-level arrays, parent-pointer arrays. The hash map approach generalizes any flat encoding to parent-child lookups. Path Sum IV is a great problem for understanding how tree algorithms adapt to non-standard representations.

Similar Questions