Problem solution · Java

Collect Coins in a Tree

Collect Coins in a Tree: a Java solution using hash-based lookup. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Hash-based lookup
Source
walkccc LeetCode Solutions
Length
49 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Hash-based lookup

For Collect Coins in a Tree, the implementation stores previously seen values or frequencies in a hash table for direct membership and lookup operations.

  1. Decide the key that represents the information needed later.
  2. Update its count or stored state while scanning the input.
  3. Use constant-time expected lookups to detect matches or assemble the result.

Code notes

  • 49 lines of Java from the credited upstream file 2603.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
  • 6 loop blocks detected.

Complexity

Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCollect Coins in a Tree · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int collectTheCoins(int[] coins, int[][] edges) {    final int n = coins.length;    Set<Integer>[] tree = new Set[n];    Deque<Integer> leavesToBeRemoved = new ArrayDeque<>();     for (int i = 0; i < n; ++i)      tree[i] = new HashSet<>();     for (int[] edge : edges) {      final int u = edge[0];      final int v = edge[1];      tree[u].add(v);      tree[v].add(u);    }     for (int i = 0; i < n; ++i) {      int u = i;      // Remove the leaves that don't have coins.      while (tree[u].size() == 1 && coins[u] == 0) {        final int v = tree[u].iterator().next();        tree[u].clear();        tree[v].remove(u);        u = v; // Walk up to its parent.      }      // After trimming leaves without coins, leaves with coins may satisfy      // `leavesToBeRemoved`.      if (tree[u].size() == 1)        leavesToBeRemoved.offer(u);    }     // Remove each remaining leaf node and its parent. The remaining nodes are    // the ones that must be visited.    for (int i = 0; i < 2; ++i)      for (int sz = leavesToBeRemoved.size(); sz > 0; --sz) {        final int u = leavesToBeRemoved.poll();        if (!tree[u].isEmpty()) {          final int v = tree[u].iterator().next();          tree[u].clear();          tree[v].remove(u);          if (tree[v].size() == 1)            leavesToBeRemoved.offer(v);        }      }     return Arrays.stream(tree).mapToInt(children -> children.size()).sum();  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗