Ctrl K

Repaint a Path in One Shade

Hard
You are given a tree of node_count nodes numbered 0 to node_count - 1. Each link links[i] = [a, b, c] joins nodes a and b and is painted in shade c, a number from 1 to 26. Each query queries[j] = [x, y] asks: what is the smallest number of links to repaint so that every link on the path between x and y has the same shade? A link can be repainted in any shade. Queries are independent: before each one the tree goes back to its original colouring. If x = y, the path is empty and the answer is 0. Return the answers in query order.
Example 1
node_count=5, links=[[0, 1, 3], [1, 2, 3], [1, 3, 7], [3, 4, 3]], queries=[[0, 2], [2, 4], [4, 4]] → [0, 1, 0]

The path 0–1–2 is already all shade 3. The path 2–1–3–4 has shades 3, 7, 3, so one link (1–3) is repainted. A path from a node to itself is empty, so nothing is needed.

Example 2
node_count=4, links=[[0, 1, 1], [0, 2, 2], [0, 3, 3]], queries=[[1, 2], [3, 3], [2, 3]] → [1, 0, 1]

The path 1–0–2 has two links of different shades, so one of them must be repainted.

Constraints
  • 1 ≤ node_count ≤ 10⁴
  • len(links) = node_count - 1, and the links form a tree
  • links[i] = [a, b, c], 0 ≤ a, b < node_count, 1 ≤ c ≤ 26
  • 1 ≤ len(queries) ≤ 2·10⁴
  • queries[j] = [x, y], 0 ≤ x, y < node_count
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Path Without Twin Neighbours HardRoutes Between Equal Peaks HardCoin Pickup Round Trip HardDiscounted Trips Through a Tree HardRooms Open from the Hall Medium
loading Python…
Input
node_count=5, links=[[0, 1, 3], [1, 2, 3], [1, 3, 7], [3, 4, 3]], queries=[[0, 2], [2, 4], [4, 4]]
Expected
[0, 1, 0]

Run checks the first 3 tests in your browser. Submit checks all 28 tests on the server, hidden ones included.