Browse curriculum

Matrices

The Matrices Pattern

A 2D grid is a graph whose neighbours are implicit: each cell connects to the cells beside it. Most matrix problems are BFS, DFS or DP with row and column bookkeeping, plus in-place tricks for rotation and traversal.

3

Interactive problems

1

Free to open

Recognise

How do you recognise a matrices problem?

The input is a 2D grid and the question involves islands, regions, flood fill, spiral or diagonal traversal, path counting, or rotating and transposing in place.

Complexity

What is the time complexity of the matrices pattern?

O(rows × cols) for a full traversal. In-place transformations keep space at O(1) beyond the input.

Problems

Matrices practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Matrices problems by difficulty and complexity

The difficulty, running time and extra space of every matrices solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Spiral MatrixMediumΩ(m·n)Θ(m·n)O(m·n)O(1)
Rotate ImageMediumΩ(n²)Θ(n²)O(n²)O(1)
Set Matrix ZeroesMediumΩ(m·n)Θ(m·n)O(m·n)O(1)
Curriculum

Matrices is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern