← PayPal bank

PayPal · Question 9 · Arrays

Rotate Image

ArraysJavacode⏱ O(n^2)💾 O(1)
Product-based

Problem

Rotate an n x n 2D matrix 90 degrees clockwise in-place.

Approach

Transpose the matrix then reverse each row.

Time O(n^2)Space O(1)

How it works

  1. 1Transpose across the diagonal.
  2. 2Reverse every row.

Sample input / output

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

Constraints

n == matrix.length; 1 <= n <= 20; in place.

Solution — read it, then walk it

Time O(n^2)Space O(1)Loops 4source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static voidrotate(int[][] matrix)DEFINE n = matrix.lengthTransposefor (int i = 0; i < n;i++)for (int j = i; j < n;j++)DEFINE temp = matrix[i][j]matrix[i][j] = matrix[j][i]matrix[j][i] = tempReverse rowsfor (int i = 0; i < n;i++)DEFINE left = 0, right = n- 1while (left < right)DEFINE temp =matrix[i][left]matrix[i][left] =matrix[i][right]matrix[i][right] = templeft++right--DEFINE static voidmain(String[] args)DEFINE [][] m = {{1, 2, 3},{4, 5, 6}, {7, 8, 9}}rotate(m)System.out.println(Arrays.deepToString(m))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/24

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits