Why does this in-place matrix rotation corrupt values on the inner layer?

BobaMilk
Fri, 03 Apr 2026 20:00:10 +0000

I’m rotating an n x n matrix 90° clockwise in place. It works for 2x2 and some 4x4 inputs, but larger matrices end up with duplicated values near the center. I suspect my layer/offset math is wrong, but I can’t spot it.

function rotate(m) {
  const n = m.length;
  for (let layer = 0; layer < n / 2; layer++) {
    for (let i = layer; i < n - layer - 1; i++) {
      const top = m[layer][i];
      m[layer][i] = m[n - 1 - i][layer];
      m[n - 1 - i][layer] = m[n - 1 - layer][n - 1 - i];
      m[n - 1 - layer][n - 1 - i] = m[i][n - 1 - layer];
      m[i][n - 1 - layer] = top;
    }
  }
}

What index calculation is off here?

BobaMilk