#1766

Tree of Coprimes

Hard
ArrayMathTreeDepth-First SearchNumber TheoryHash MapDepth-First SearchNumber Theory
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a depth-first search (DFS) while maintaining a map of the last seen node values. This allows us to efficiently find the closest coprime ancestor without redundant checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a graph representation of the tree using adjacency lists.
  2. 2Step 2: Use a DFS to traverse the tree, maintaining a HashMap to track the last seen node for each value.
  3. 3Step 3: For each node, check the HashMap for coprime values and update the answer accordingly.
solution.py23 lines
1from math import gcd
2from collections import defaultdict
3
4def coprime_ancestors(nums, edges):
5    n = len(nums)
6    graph = [[] for _ in range(n)]
7    for u, v in edges:
8        graph[u].append(v)
9        graph[v].append(u)
10    ans = [-1] * n
11    last_seen = defaultdict(int)
12    def dfs(node, parent):
13        for value in last_seen:
14            if gcd(nums[node], value) == 1:
15                ans[node] = last_seen[value]
16                break
17        last_seen[nums[node]] = node
18        for neighbor in graph[node]:
19            if neighbor != parent:
20                dfs(neighbor, node)
21        del last_seen[nums[node]]
22    dfs(0, -1)
23    return ans

Complexity note: The complexity is O(n) because we visit each node once and maintain a HashMap for the last seen nodes, which allows for efficient lookups.

  • 1Using a HashMap to track last seen values can significantly reduce the number of checks needed.
  • 2Understanding the properties of coprime numbers and gcd is crucial for optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.