← Deloitte bank

Deloitte · Question 31

Rotate Image

Javacode⏱ O(n²)💾 O(1)
Service-based

Problem

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

Approach

Transpose then reverse each row.

Time O(n²)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 x n; 1 <= n <= 20; in place.

Solution — read it, then walk it

Time O(n²)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.lengthfor (int i = 0; i < n;i++)for (int j = i; j < n;j++)DEFINE t = matrix[i][j]matrix[i][j] = matrix[j][i]matrix[j][i] = tfor (int i = 0; i < n;i++)for (int j = 0; j < n/ 2; j++)DEFINE t = matrix[i][j]matrix[i][j] = matrix[i][n- 1 - j]matrix[i][n - 1 - j] = tDEFINE 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/19

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