Skip to content
We areTOP 1%
DSA · Beginner · Pattern 4 of 11

Matrix (2-D Arrays)

10 problems.
Your progress0%
1st Visit
0/10
2nd Visit
0/10
Revise
0/10

About this pattern

A matrix is a 2-D array indexed by row and column; visiting all m * n cells costs O(m * n). Most problems combine a few moves: scanning rows or columns, walking the diagonals (i == j and i + j == n - 1), peeling the grid layer by layer, checking a cell's four neighbours with direction arrays, and transforming in place by swapping mirrored cells.

Recognise the pattern when the input is a grid, board or table, or when the statement mentions rows, columns, diagonals, rotation or spirals. Grids need not be square, so keep m and n separate and check both bounds before reading a neighbour.

// Row-major traversal of an m x n grid.
for (int r = 0; r < m; ++r)
    for (int c = 0; c < n; ++c)
        visit(grid[r][c]);

// Four side neighbours of (r, c), skipping cells outside the grid.
int dr[4] = {-1, 1, 0, 0}, dc[4] = {0, 0, -1, 1};
for (int k = 0; k < 4; ++k) {
    int nr = r + dr[k], nc = c + dc[k];
    if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
    visit(grid[nr][nc]);
}

// Flattened index: cell (r, c) <-> r * n + c.

Problems

Matrix (2-D Arrays) questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Matrix Diagonal SumLeetCodeEasy Solve Matrix Diagonal Sum on LeetCode (opens in a new tab)
2Beautiful MatrixCodeforcesEasy 800Solve Beautiful Matrix on Codeforces (opens in a new tab)
3Transpose MatrixLeetCodeEasy Solve Transpose Matrix on LeetCode (opens in a new tab)
4Target PracticeCodeforcesEasy 800Solve Target Practice on Codeforces (opens in a new tab)
5Pascal's TriangleLeetCodeEasy Solve Pascal's Triangle on LeetCode (opens in a new tab)
6Lights OutCodeforcesEasy 900Solve Lights Out on Codeforces (opens in a new tab)
7Set Matrix ZeroesLeetCodeMedium Solve Set Matrix Zeroes on LeetCode (opens in a new tab)
8Valid SudokuLeetCodeMedium Solve Valid Sudoku on LeetCode (opens in a new tab)
9Rotate ImageLeetCodeMedium Solve Rotate Image on LeetCode (opens in a new tab)
10Spiral MatrixLeetCodeMedium Solve Spiral Matrix on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account