KatInterview

Rainbow Walks of Length Three in a Typed Graph

Trees & GraphsAuto-graded · 26 test cases
MediumAuto-gradedTrees & Graphsgraphcountingcombinatorics

Last 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, 2 and 3 in some order (each category appears exactly once), and
  • a street joins p0 and p1, a street joins p1 and p2, and a street joins p2 and p3.

Input

  • shops: a list of integers, where shops[i] is the category of location i.
  • roads: a list of pairs [a, b], each meaning there is a two-way street between locations a and b.

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) <= 50
  • 0 <= shops[i] <= 3
  • 0 <= len(roads) <= 250
  • Each road is [a, b] with 0 <= a, b < len(shops) and a != 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.