2D arrays
diagonal filling
coordinate-based arrays
programming
algorithms

How to fill a 2D array diagonally based on coordinates

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Diagonal fills become much easier once you stop thinking about repeated boundary checks and instead think about the property that defines a diagonal. In a matrix, every cell on the same main diagonal shares the same row - col value, and every cell on the same anti-diagonal shares the same row + col value.

Use The Coordinate To Identify The Diagonal

Suppose the target coordinate is (row, col). For the top-left to bottom-right diagonal, every matching cell has the same difference between row and column.

That means you do not need to walk backward to find the start first. You can compute the diagonal key once and then scan each row:

python
1def fill_main_diagonal(matrix, row, col, value):
2    rows = len(matrix)
3    cols = len(matrix[0]) if rows else 0
4
5    if not (0 <= row < rows and 0 <= col < cols):
6        raise ValueError("coordinate is outside the matrix")
7
8    diagonal_key = row - col
9
10    for r in range(rows):
11        c = r - diagonal_key
12        if 0 <= c < cols:
13            matrix[r][c] = value

This works for square and rectangular matrices because the column index is checked against cols on each iteration.

Fill The Anti-Diagonal

For the other direction, the invariant changes. Every cell on the same anti-diagonal has the same row + col total.

python
1def fill_anti_diagonal(matrix, row, col, value):
2    rows = len(matrix)
3    cols = len(matrix[0]) if rows else 0
4
5    if not (0 <= row < rows and 0 <= col < cols):
6        raise ValueError("coordinate is outside the matrix")
7
8    diagonal_sum = row + col
9
10    for r in range(rows):
11        c = diagonal_sum - r
12        if 0 <= c < cols:
13            matrix[r][c] = value

This is often easier to reason about than hand-written while loops because the traversal rule is expressed directly from the coordinate.

Test The Result On A Small Matrix

When working on matrix problems, a compact test harness is worth writing immediately. It helps you spot off-by-one errors before the real algorithm becomes more complicated.

python
1def make_matrix(rows, cols):
2    return [[0 for _ in range(cols)] for _ in range(rows)]
3
4
5grid = make_matrix(5, 6)
6fill_main_diagonal(grid, 3, 2, 7)
7
8for row in grid:
9    print(row)

If the coordinate is (3, 2), the filled cells should lie on the same top-left to bottom-right line as that point. Repeat the same test with fill_anti_diagonal to confirm the opposite direction.

Fill With A Sequence Instead Of One Constant

Sometimes the task is not "set every diagonal cell to 1." You may need to place values in order, such as 1, 2, 3, or copy values from another list. The easiest way is to generate the diagonal coordinates first and then fill them.

python
1def main_diagonal_positions(rows, cols, row, col):
2    diagonal_key = row - col
3    positions = []
4
5    for r in range(rows):
6        c = r - diagonal_key
7        if 0 <= c < cols:
8            positions.append((r, c))
9
10    return positions
11
12
13grid = make_matrix(5, 6)
14for index, (r, c) in enumerate(main_diagonal_positions(5, 6, 3, 2), start=1):
15    grid[r][c] = index
16
17for row in grid:
18    print(row)

This split between "find coordinates" and "write values" is useful when the fill logic becomes more advanced, such as alternating colors on a board, copying image pixels, or writing path costs in a dynamic programming table.

Know When Traversal Order Matters

If the article or interview question only asks which cells belong to the same diagonal, the invariant-based approach is enough. If it also cares about order, be explicit about it. For example, one caller may want top-to-bottom order, while another may want the fill to start from the chosen coordinate and expand outward.

The underlying diagonal membership rule stays the same. What changes is the order in which you visit the valid coordinates. Keeping those concerns separate makes the implementation easier to adapt.

Common Pitfalls

  • Forgetting that the two diagonal directions use different invariants.
  • Assuming the matrix is square when the code should work for rectangular grids.
  • Starting from the coordinate and filling only one direction instead of the full diagonal.
  • Skipping input validation and then chasing index errors later.
  • Mixing diagonal membership logic with value-generation logic in one hard-to-read loop.

Summary

  • A main diagonal through a coordinate is defined by a constant row - col.
  • An anti-diagonal through a coordinate is defined by a constant row + col.
  • Computing the diagonal key first often leads to cleaner code than manually walking to an edge.
  • Separate "which cells belong to the diagonal" from "what value should be written there."

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms