Ctrl K

A Chain of Domino Tiles

Hard
You are given a set of tiles tiles, each a pair of numbers [left, right]. Tiles cannot be flipped. Lay all of them in a single chain so that the right number of every tile equals the left number of the tile after it. The input guarantees that such a chain exists and is unique, with one exception: if the tiles close into a loop (the right number of the last tile equals the left number of the first), the loop could start anywhere, and in that case the chain must start with the tile tiles[0]. Return the chain as the list of tiles in order.
Example 1
tiles=[[7, 2], [4, 7], [2, 9]] → [[4, 7], [7, 2], [2, 9]]

The chain is 4→7, 7→2, 2→9: the right number of every tile matches the left number of the next one.

Example 2
tiles=[[5, 8], [3, 5], [8, 3]] → [[5, 8], [8, 3], [3, 5]]

The tiles close into a loop 5→8→3→5, so the chain starts with the first tile [5, 8].

Example 3
tiles=[[1, 2], [2, 1], [1, 3]] → [[1, 2], [2, 1], [1, 3]]

The number 1 appears on the left twice and on the right once, so the chain starts at 1. Laying [1, 3] first leaves nothing to attach to the 3, so [1, 2] goes first.

Constraints
  • 1 ≤ len(tiles) ≤ 10⁵
  • 0 ≤ left, right ≤ 10⁹
  • left ≠ right
  • No two tiles are identical
  • The chain exists and is unique (given the loop rule)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRoute Through Every Boarding Pass HardEvery Code in One Entry HardLetter Order From a Dictionary HardLongest Uphill Walk HardBall Into the Hole Hard
loading Python…
Input
tiles=[[7, 2], [4, 7], [2, 9]]
Expected
[[4, 7], [7, 2], [2, 9]]

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