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

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 :blush:

Your swaps are actually consistent.

WaffleFries

Can you provide a before and after example of a matrix that you rotate the values 90 degrees by? I’m having difficulty visualizing this.

Before:1 2 3 4 5 6 7 8 9After a 90° clockwise rotation:7 4 1 8 5 2 9 6 3A good debugging signal is to label a 4x4 with unique values and watch one inner-layer cycle, like 6 -> 10 -> 11 -> 7 -> 6; if that loop breaks or repeats early, the layer bounds are wrong, not the swap order.

WaffleFries

Can you format that in a code block so the rows and columns can be seen? It is hard to map as a flat list.

Another clean way to visualize it is as a grid instead of a flat list:text Before: 1 2 3 4 5 6 7 8 9 After 90° clockwise: 7 4 1 8 5 2 9 6 3 That tradeoff helps readability more than showing the raw traversal order, which is usually better once you start checking the inner-layer index math.

WaffleFries