Problems > Number Spiral > Editorial

Number Spiral — Solution & Editorial

Back to the Problem

Let k = max(R, C). Ring k holds (k−1)²+1 .. k². For odd k the ring runs up column k then leftwards along row k ending with k² at (k, 1); for even k it is mirrored. Case-split on parity and which side of the corner (R, C) sits.

Complexity: O(1)

Watch out: Values reach 1018 — 64-bit; and the parity mirroring is exactly where off-by-ones hide.