Find Number of Coins to Place in Tree Nodes — LeetCode 2973 Python Solution

HardTreeDepth-First SearchDynamic ProgrammingSortingHeap (Priority Queue)
Problem
#2973
Reading time
4 min

The problem

You are given an undirected tree with n nodes labeled from 0 to n - 1, and rooted at node 0. You are given a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Example

Input
edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6]
Output
[120,1,1,1,1,1]
Explanation
For node 0 place 6 * 5 * 4 = 120 coins. All other nodes are leaves with subtree of size 1, place 1 coin on each of them.

Python solution

Python
class Solution:
    def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]:
        def dfs(a: int, fa: int) -> List[int]:
            res = [cost[a]]
            for b in g[a]:
                if b != fa:
                    res.extend(dfs(b, a))
            res.sort()
            if len(res) >= 3:
                ans[a] = max(res[-3] * res[-2] * res[-1], res[0] * res[1] * res[-1], 0)
            if len(res) > 5:
                res = res[:2] + res[-3:]
            return res

        n = len(cost)
        g = [[] for _ in range(n)]
        for a, b in edges:
            g[a].append(b)
            g[b].append(a)
        ans = [1] * n
        dfs(0, -1)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2973. Find Number of Coins to Place in Tree Nodes is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2973. Find Number of Coins to Place in Tree Nodes?
LeetCode 2973. Find Number of Coins to Place in Tree Nodes is rated Hard on LeetCode.
What is the time complexity of LeetCode 2973. Find Number of Coins to Place in Tree Nodes?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2973. Find Number of Coins to Place in Tree Nodes?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2973. Find Number of Coins to Place in Tree Nodes cover?
LeetCode 2973. Find Number of Coins to Place in Tree Nodes is tagged Tree, Depth-First Search, Dynamic Programming, Sorting and Heap (Priority Queue) on LeetCode.

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