Rainbow Walks of Length Three in a Typed Graph
Trees & GraphsAuto-graded · 26 test casesLast updated
Count ordered 4-vertex walks along edges in an undirected graph whose vertices carry one of four labels, where each walk uses every label exactly once.
Rainbow Walks of Length Three in a Typed Graph
A city map has several locations, and every location belongs to exactly one of four categories, labelled 0, 1, 2 and 3. Some pairs of locations are joined by a two-way street.
You are asked to count the rainbow routes on this map: sequences of four locations [p0, p1, p2, p3] in which
- the categories of the four locations are
0,1,2and3in some order (each category appears exactly once), and - a street joins
p0andp1, a street joinsp1andp2, and a street joinsp2andp3.
Input
shops: a list of integers, whereshops[i]is the category of locationi.roads: a list of pairs[a, b], each meaning there is a two-way street between locationsaandb.
Output
Return a single integer: the number of rainbow routes.
Rules
- Streets can be travelled in both directions.
- Routes are ordered sequences. The same four locations visited in a different order are a different route, and a route and its reverse are counted as two separate routes.
- Since each category appears exactly once, the four locations in a route are automatically distinct, and a route has exactly four locations.
- If some category does not appear anywhere, or no valid route exists, return
0.
Constraints
1 <= len(shops) <= 500 <= shops[i] <= 30 <= len(roads) <= 250- Each road is
[a, b]with0 <= a, b < len(shops)anda != b. - No street is listed twice: the input never contains both
[a, b]and[b, a], and never repeats a pair. - The answer is at most
50 * 49 * 48 * 47 = 5,527,200.
Examples
Example 1
Input: count_rainbow_routes([1, 0, 3, 2, 2], [[0, 1], [1, 2], [1, 4], [2, 3], [2, 4]])
Output: 6
Example 2
Input: count_rainbow_routes([0, 1, 2, 3], [[0, 1], [1, 2], [2, 3], [3, 0]])
Output: 8
Example 3
Input: count_rainbow_routes([0, 1, 1, 2], [[0, 1], [1, 2], [2, 3], [0, 2]])
Output: 0
Hints
Hint 1
Because the four categories are all different, the four locations in a route are automatically distinct. You do not need to track visited nodes.
Hint 2
Instead of enumerating every 4-tuple, fix the middle street (p1, p2) in a particular direction. Its two endpoints must have different categories, which leaves exactly two categories for p0 and p3.
Hint 3
For a fixed ordered middle street (b, c), count the neighbours of b and of c by category. With leftover categories x and y, the number of routes is cnt_b[x]*cnt_c[y] + cnt_b[y]*cnt_c[x]. Summing over both directions of every street handles reversed routes.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every rainbow route is [a, b, c, d]. Rather than enumerating all 4-tuples, enumerate the middle street (b, c) as an ordered pair (so each street is considered in both directions).
- Skip the pair if
bandchave the same category, since a rainbow route needs four different categories. - The two remaining categories, call them
xandy, must be taken byaandd. amust be a neighbour ofbandda neighbour ofc. Eitherahas categoryxanddhas categoryy, or the other way around. Ifhist[v][k]is the number of neighbours ofvwith categoryk, the contribution ishist[b][x] * hist[c][y] + hist[b][y] * hist[c][x].
Summing over all ordered middle streets gives the answer.
Why it is correct
- Distinctness is automatic. The four categories are pairwise different, so the four locations are pairwise different. No explicit checks such as
a != care needed. - Every route is counted. For a valid route
[p0, p1, p2, p3], the iteration withb = p1,c = p2has leftover categories equal to those ofp0andp3, andp0is a neighbour ofp1whilep3is a neighbour ofp2, so it appears in one of the two products. - No route is counted twice. The ordered pair
(p1, p2)identifies the middle of the route, and the category ofp0decides which product term includes it. - Reversals are separate. The reverse route has the middle pair
(p2, p1), a different iteration, so both directions are counted, as required.
Complexity
- Time:
O(n + E)to build adjacency lists and category histograms, plusO(1)per ordered street, soO(n + E)overall. - Space:
O(n + E).
Reference solution
from typing import List
def count_rainbow_routes(shops: List[int], roads: List[List[int]]) -> int:
n = len(shops)
adj = [[] for _ in range(n)]
for a, b in roads:
adj[a].append(b)
adj[b].append(a)
# hist[v][k] = number of neighbours of v with category k
hist = [[0] * 4 for _ in range(n)]
for v in range(n):
for u in adj[v]:
hist[v][shops[u]] += 1
total = 0
for b in range(n):
kb = shops[b]
for c in adj[b]:
kc = shops[c]
if kb == kc:
continue
x, y = [k for k in range(4) if k != kb and k != kc]
total += hist[b][x] * hist[c][y] + hist[b][y] * hist[c][x]
return total