Skip to content

Instantly share code, notes, and snippets.

@evgkarasev
Last active July 12, 2020 10:40
Show Gist options
  • Save evgkarasev/f76cf65ea3108b084a685b70aaeee1a4 to your computer and use it in GitHub Desktop.
Save evgkarasev/f76cf65ea3108b084a685b70aaeee1a4 to your computer and use it in GitHub Desktop.
How to rotate a two dimensional array in javascript?

O(n^2) time and O(1) space algorithm

Rotate by +90:

  1. Transpose
  2. Reverse each row

Rotate by -90:

Method 1 :

  1. Transpose
  2. Reverse each column

Method 2 :

  1. Reverse each row
  2. Transpose

Rotate by +180:

Method 1: Rotate by +90 twice

Method 2: Reverse each row and then reverse each column (Transpose)

Rotate by -180:

Method 1: Rotate by -90 twice

Method 2: Reverse each column and then reverse each row

Method 3: Rotate by +180 as they are same

let array = [[0, 1, 0], [1, 1, 1]];
function rotate(array) {
return array[0].map((_, index) => array.map(row => row[index]).reverse());
}
let array90 = rotate(array);
let array180 = rotate(array90);
console.log(array);
console.log(array90);
console.log(array180);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment