Path Sum IV — LeetCode 666 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchArrayHash TableBinary Tree
Problem
#666
Reading time
4 min

The problem

If the depth of a tree is smaller than 5, then this tree can be represented by an array of three-digit integers. You are given an ascending array nums consisting of three-digit integers representing a binary tree with a depth smaller than 5, where for each integer: The hundreds digit represents the depth d of this node, where 1 <= d <= 4.

Python solution

Python
class Solution:
    def pathSum(self, nums: List[int]) -> int:
        def dfs(node, t):
            if node not in mp:
                return
            t += mp[node]
            d, p = divmod(node, 10)
            l = (d + 1) * 10 + (p * 2) - 1
            r = l + 1
            nonlocal ans
            if l not in mp and r not in mp:
                ans += t
                return
            dfs(l, t)
            dfs(r, t)

        ans = 0
        mp = {num // 10: num % 10 for num in nums}
        dfs(11, 0)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 666. Path Sum IV is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 666. Path Sum IV?
LeetCode 666. Path Sum IV is rated Medium on LeetCode.
What is the time complexity of LeetCode 666. Path Sum IV?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 666. Path Sum IV?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 666. Path Sum IV cover?
LeetCode 666. Path Sum IV is tagged Tree, Depth-First Search, Array, Hash Table and Binary Tree on LeetCode.
Is LeetCode 666. Path Sum IV a premium problem?
Yes. LeetCode 666. Path Sum IV is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview