Skip to the code
+25 XP

#452 Assign Light and Dark Tiles

medium

A dashboard alternates light and dark tiles so that tiles sharing a border always look different. Tiles are numbered 0 to n - 1, and borders[i] = [a, b] means tiles a and b share a border.

Write assignThemes(n, borders) that returns an array where entry i is 0 (light) or 1 (dark) for tile i, so that every pair in borders gets different values. To make the answer unique: in every group of tiles connected by borders, the smallest-numbered tile is light (0). If no valid assignment exists, return [].

Example 1

Input: n = 4, borders = [[0,1],[1,2],[3,2]]
Output: [0,1,0,1]

Tile 0 is light, so 1 is dark, 2 is light, and 3 is dark.

Example 2

Input: n = 3, borders = [[0,1],[1,2],[2,0]]
Output: []

Three tiles that all touch each other can't alternate between two themes.

Constraints

  • 1 <= n <= 10^5
  • 0 <= borders.length <= 2 * 10^5
  • 0 <= a, b < n, a !== b
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).