progress

~/problems / Graphs / Bipartite graphs / 2-colouring

Day and night shifts with fixed staff

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A lighthouse crew 0 .. n-1 splits into a day shift (0) and a night shift (1). Each pair (a, b) in handovers must be on different shifts. fixed maps some people to the shift they insist on.

Implement assign_shifts(n, handovers, fixed) -> list[int] | None: a valid shift for everyone, or None if impossible. Any valid answer is accepted.

assign_shifts(4, [(0, 1), (1, 2)], {2: 0})     # [0, 1, 0, 0]  (person 3 could be 1 as well)
assign_shifts(3, [(0, 1), (1, 2)], {0: 0, 2: 1})   # None: 0 and 2 must share a shift
assign_shifts(3, [(0, 1), (1, 2), (2, 0)], {})     # None: odd cycle

Up to 10^5 people and 2 * 10^5 handovers. A pair (v, v) can never be satisfied.

⭐ Bonus: speed tests with 100,000 people earn a star with one BFS per group, O(n + handovers).

Show hint

each connected group's colouring is forced up to a swap. BFS it from a fixed person if it has one, otherwise from anyone with shift 0; then check every edge and fixed person.

Topic: Bipartite graphs / 2-colouring. BFS/DFS colouring; an odd cycle means not bipartite.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc