Rotate matrix by 90 degrees

Arrays FAQs(Medium) Medium
  • One interesting application of this problem can be found in image processing
  • Many image-editing software or applications use rotation algorithms similar to this to adjust or manipulate images
  • For instance, when you rotate an image 90 degrees clockwise on your smartphone or computer, programs effectively apply a similar method in the background

Given an N * N 2D integer matrix, rotate the matrix by 90 degrees clockwise.


The rotation must be done in place, meaning the input 2D matrix must be modified directly.

Examples:

Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output: matrix = [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Input: matrix = [[0, 1, 1, 2], [2, 0, 3, 1], [4, 5, 0, 5], [5, 6, 7, 0]]

Output: matrix = [[5, 4, 2, 0], [6, 5, 0, 1], [7, 0, 3, 1], [0, 5, 1, 2]]

Input: matrix = [[1, 1, 2], [5, 3, 1], [5, 3, 5]]

Constraints

  • n == matrix.length.
  • n == matrix[i].length.
  • 1 <= n <= 100.
  • -104 <= matrix[i][j] <= 104

Hints

  • Swap elements such that matrix[i][j] becomes matrix[j][i]. Reverse the order of elements in each row to complete the rotation.
  • Alternatively, rotate the matrix in layers, starting from the outermost layer and moving inward. For each layer, shift elements in groups of four.

Company Tags

Snowflake Epic Games Freshworks Bungie Robinhood Boston Consulting Group OYO Rooms Philips Healthcare Ernst & Young Visa Lyft Texas Instruments McKinsey & Company Chewy DoorDash Goldman Sachs Pinterest Wayfair Roblox Ubisoft Splunk Target Swiggy American Express Intel TCS Cognizant Accenture Infosys Capgemini Wipro