Click here to Skip to main content
15,887,776 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
how to rotate a square matrix by 90degrees with O(1) extra space????
Posted
Comments
joshrduncan2012 26-Feb-13 11:04am    
What have you done to accomplish this so far? Where are you stuck?
Sandeep Mewara 26-Feb-13 11:19am    
Ditto!
Sergey Alexandrovich Kryukov 26-Feb-13 14:15pm    
This is one of those relatively tricky interview questions which mostly need some mathematical and logical thinking, not much more. I don't like such questions much, but it's not that bad...
OP just need to think...
I have only one advice to OP: don't give up. Not a rocket surgery, by the way...
—SA
Manfred Rudolf Bihy 26-Feb-13 16:07pm    
You're really amusing me with your slightly "off key" idioms!
I'm not sure though if you're doing this on purpose or by accident, hmmmm.
;)

Sergey Alexandrovich Kryukov 26-Feb-13 16:37pm    
Thank you for asking, I'll gladly answer you, but I'm a bit confusing: which one, literally?
If this is "rocket surgery", this is intentional, and not my invention. Or are you talking about something else? What's "off-key"?
—SA

1 solution

See the matrix as a set of nested squares. You can rotate each square independently. To rotate a square by N positions, you can rotate it N times by one position. To rotate by one position, save one element to extra storage, shift the others circularly and put back the saved element.
A B C D E
P       F
O       G
N       H
M L K J I

- B C D E     A
P       F
O       G
N       H
M L K J I

B C D E -     A
P       F
O       G
N       H
M L K J I

B C D E F     A
P       G
O       H
N       I
M L K J -

B C D E F     A
P       G
O       H
N       I
- M L K J

B C D E F     A
-       G
P       H
O       I
N M L K J

B C D E F
A       G
P       H
O       I
N M L K J
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900