← Accenture bank

Accenture · Question 12 · Arrays

Rotate Image (90 degrees)

ArraysC++code⏱ O(n²)💾 O(1)
Service-based

Problem

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

Approach

First transpose the matrix, 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 matrix; 1 <= n <= 20; in place.

Solution — read it, then walk it

Time O(n²)Space O(1)Loops 5Branches 2Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeat↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <algorithm>using namespace stdDEFINErotate(vector<vector<int>>&matrix)DEFINE n = matrix.size()Transposefor (int i = 0; i < n;++i)for (int j = i; j < n;++j)std::swap(matrix[i][j],matrix[j][i])Reverse each rowfor (int i = 0; i < n;++i)std::reverse(matrix[i].begin(),matrix[i].end())DEFINE main()vector<vector<int>> m ={{1, 2, 3}, {4, 5, 6}, {7,8, 9}}rotate(m)cout << "["for (size_t i = 0; i <m.size(); ++i)if (i) cout << ", "cout << "["for (size_t j = 0; j <m[i].size(); ++j)if (j) cout << ", "cout << m[i][j]cout << "]"cout << "]" << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/27

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