Fewest forced layouts for a batch of DOM reads and writes

Write codeHard40 min

Your task

A page runs one batch of DOM operations collected from many components. Each operation either reads layout (R, like reading offsetHeight) or writes something that affects it (W, like setting a width). kinds[i] is the kind of operation i, and each pair [a, b] in deps means operation a must run before operation b. The dependencies never form a cycle, and a pair may repeat. Every operation runs exactly once, in any order that respects deps.

Layout starts clean. A write makes it dirty. A read while layout is dirty forces a synchronous layout, which makes it clean again; a read on clean layout costs nothing, and so does leaving layout dirty at the end. Return the smallest number of forced layouts that any valid order achieves. A batch can hold hundreds of operations, so trying orders one by one will not finish.

Examples:

  • min_forced_layouts("WRWR", [[0, 1], [2, 3]]) returns 1: run both writes, then both reads.
  • min_forced_layouts("RWR", [[0, 1], [1, 2]]) returns 1: whatever the order, the second read comes after the write.
  • min_forced_layouts("WRW", [[1, 2]]) returns 0: the read runs first, then both writes.

Examples

min_forced_layouts(kinds: str, deps: list[list[int]]) -> int
Example 1
Inputmin_forced_layouts("WRWR", [[0, 1], [2, 3]])
Output1
Example 2
Inputmin_forced_layouts("RWR", [[0, 1], [1, 2]])
Output1
Example 3
Inputmin_forced_layouts("WRW", [[1, 2]])
Output0