CodexBloom - Programming Q&A Platform

JavaScript - How to Efficiently Rotate a 2D Array Without Creating a New Array?

👀 Views: 94 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-24
arrays in-place algorithms JavaScript

I'm stuck on something that should probably be simple. Quick question that's been bugging me - I'm currently working on a 2D array manipulation in JavaScript and working with an scenario with rotating a matrix in place... The goal is to rotate a given matrix 90 degrees clockwise without creating a new array, to optimize for space. I've tried a few methods but I'm struggling with the correct indexing and ensuring that I don't overwrite the elements prematurely. For instance, given the following matrix: ```javascript let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; ``` The expected output after rotation should be: ```javascript [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ]; ``` I initially tried to do this with nested loops, but the results were incorrect due to the overwriting of values. Here's what I attempted: ```javascript function rotate(matrix) { let n = matrix.length; for (let layer = 0; layer < n / 2; layer++) { let first = layer; let last = n - 1 - layer; for (let i = first; i < last; i++) { let offset = i - first; let top = matrix[first][i]; // save top // left -> top matrix[first][i] = matrix[last - offset][first]; // bottom -> left matrix[last - offset][first] = matrix[last][last - offset]; // right -> bottom matrix[last][last - offset] = matrix[i][last]; // top -> right matrix[i][last] = top; // right <- saved top } } } ``` However, when I run this code, I get a distorted output. For example, rotating the matrix results in: ```javascript [ [7, 2, 3], [6, 5, 4], [1, 8, 9] ]; ``` It seems like I'm not managing the indices correctly. Can someone guide to figure out how to correctly rotate this 2D array in place? I want to ensure that no additional arrays are created, and I'm particularly interested in understanding how to manage the indices properly during the swapping process. Any insights or corrections to my approach would be greatly appreciated! For context: I'm using Javascript on Ubuntu 20.04. I'm open to any suggestions. This issue appeared after updating to Javascript 3.11. Hoping someone can shed some light on this. The stack includes Javascript and several other technologies. Could this be a known issue?