DEV Community

Quipoin
Quipoin

Posted on

Matrix Problems Explained Simply (Java + Intuition)


Matrix problems often look intimidating.

Too many rows, columns, indices…

But most interview questions are built on just a few core patterns.

Master these patterns once,
and matrix questions become much easier.

1. Spiral Traversal

Problem

Print matrix elements in spiral order.

public static List spiralOrder(int[][] matrix) {

List<Integer> result = new ArrayList<>();

int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;

while (top <= bottom && left <= right) {

    for (int i = left; i <= right; i++)
        result.add(matrix[top][i]);

    top++;

    for (int i = top; i <= bottom; i++)
        result.add(matrix[i][right]);

    right--;

    if (top <= bottom) {
        for (int i = right; i >= left; i--)
            result.add(matrix[bottom][i]);

        bottom--;
    }

    if (left <= right) {
        for (int i = bottom; i >= top; i--)
            result.add(matrix[i][left]);

        left++;
    }
}

return result;
Enter fullscreen mode Exit fullscreen mode

}

Core Idea

Maintain 4 boundaries:

  • top
  • bottom
  • left
  • right

  • Move inward layer by layer.

2. Rotate Matrix by 90°

Trick

Instead of rotating directly:

  • Transpose matrix
  • Reverse each row

public static void rotate(int[][] matrix) {

// Transpose
for (int i = 0; i < matrix.length; i++) {
    for (int j = i; j < matrix[0].length; j++) {

        int temp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = temp;
    }
}

// Reverse rows
for (int i = 0; i < matrix.length; i++) {

    int left = 0, right = matrix[0].length - 1;

    while (left < right) {

        int temp = matrix[i][left];
        matrix[i][left] = matrix[i][right];
        matrix[i][right] = temp;

        left++;
        right--;
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Why It Works

Transpose:

  • Rows ↔ Columns

Reverse:

  • Adjust orientation

Together:

  • 90° clockwise rotation.

3. Set Matrix Zeroes

Problem

If one element is zero:

  • Entire row & column become zero.

Smart Optimization

Use:

  • First row
  • First column

as markers instead of extra space.

The Real Insight

Matrix problems are mostly about:

  • Direction handling
  • Boundary management
  • Smart index manipulation

Key Insights

  • Spiral → boundaries
  • Rotate → transpose + reverse
  • Zeroes → marker optimization

For More Learning: https://www.quipoin.com/tutorial/data-structure-with-java/matrix-problems

Top comments (0)