Inplace Rotate Square Matrix— Asked in Amazon Interviews

Problem Statement :

1 2 3
4 5 6
7 8 9
3 6 9
2 5 8
1 4 7
1  2  3   4
5 6 7 8
9 10 11 12
13 14 15 16
4  8  12 16 
3 7 11 15
2 6 10 14
1 5 9 13

Explanation of test cases :

First Cycle (Involves Red Elements)
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Moving first group of four elements (First
elements of 1st row, last row, 1st column
and last column) of first cycle in counter
clockwise.
4 2 3 16
5 6 7 8
9 10 11 12
1 14 15 13

Moving next group of four elements of
first cycle in counter clockwise
4 8 3 16
5 6 7 15
2 10 11 12
1 14 9 13
Moving final group of four elements of
first cycle in counter clockwise
4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13
Second Cycle (Involves Blue Elements)
4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13
Fixing second cycle
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
  1. There are N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2–1, the loop counter is i
  2. Consider elements in a group of 4 in the current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N — 2*i.
  3. So run a loop in each cycle from x to N — x — 1, loop counter is y
  4. The elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y) <- (y, N-1-x), (y, N-1-x)<- (N-1-x, N-1-y), (N-1-x, N-1-y)<- (N-1-y, x), (N-1-y, x)<- (x, y)
  5. Print the matrix.

Thanks for Reading

--

--

Upskilling students for tech placements!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store