matrix manipulation
diagonal numbers
algorithm
number patterns
programming guide

How to get diagonal numbers between two number in a matrix?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

To get the diagonal numbers between two values in a matrix, you first need to locate the values, then verify that their positions lie on the same diagonal. After that, the problem becomes simple index stepping. This article covers both main diagonals and anti-diagonals and shows a practical Python implementation.

When Two Matrix Elements Are Diagonal to Each Other

Suppose a value is at row r1, column c1, and another is at row r2, column c2.

They are on the same main diagonal if:

  • 'r1 - c1 == r2 - c2'

They are on the same anti-diagonal if:

  • 'r1 + c1 == r2 + c2'

If neither condition is true, there are no diagonal elements directly between them on a straight matrix diagonal.

Step 1: Find the Positions of the Two Values

You cannot reason about diagonals until you know where the numbers are.

python
1def find_position(matrix, target):
2    for r, row in enumerate(matrix):
3        for c, value in enumerate(row):
4            if value == target:
5                return r, c
6    return None
7
8
9matrix = [
10    [1, 2, 3, 4],
11    [5, 6, 7, 8],
12    [9, 10, 11, 12],
13    [13, 14, 15, 16],
14]
15
16print(find_position(matrix, 1))   # (0, 0)
17print(find_position(matrix, 11))  # (2, 2)

If values are duplicated in the matrix, define whether you want the first match or all possible matches before continuing.

Step 2: Walk the Diagonal

Once you know both coordinates, compute the step direction and collect the values strictly between the endpoints.

python
1def diagonal_between(matrix, start_value, end_value):
2    start = find_position(matrix, start_value)
3    end = find_position(matrix, end_value)
4
5    if start is None or end is None:
6        raise ValueError("One or both values are not present in the matrix")
7
8    r1, c1 = start
9    r2, c2 = end
10
11    row_diff = r2 - r1
12    col_diff = c2 - c1
13
14    if abs(row_diff) != abs(col_diff):
15        return []
16
17    step_r = 1 if row_diff > 0 else -1
18    step_c = 1 if col_diff > 0 else -1
19
20    result = []
21    r, c = r1 + step_r, c1 + step_c
22
23    while (r, c) != (r2, c2):
24        result.append(matrix[r][c])
25        r += step_r
26        c += step_c
27
28    return result
29
30
31matrix = [
32    [1, 2, 3, 4],
33    [5, 6, 7, 8],
34    [9, 10, 11, 12],
35    [13, 14, 15, 16],
36]
37
38print(diagonal_between(matrix, 1, 16))   # [6, 11]
39print(diagonal_between(matrix, 4, 13))   # [7, 10]

The abs(row_diff) == abs(col_diff) check is a compact way to confirm a shared diagonal in either direction.

Include Endpoints If Needed

Some problems want the full diagonal segment, not only the numbers between the endpoints. That is a small variation.

python
1def diagonal_segment(matrix, start_value, end_value):
2    start = find_position(matrix, start_value)
3    end = find_position(matrix, end_value)
4
5    if start is None or end is None:
6        raise ValueError("Value not found")
7
8    r1, c1 = start
9    r2, c2 = end
10
11    if abs(r2 - r1) != abs(c2 - c1):
12        return []
13
14    step_r = 1 if r2 > r1 else -1
15    step_c = 1 if c2 > c1 else -1
16
17    result = []
18    r, c = r1, c1
19    while True:
20        result.append(matrix[r][c])
21        if (r, c) == (r2, c2):
22            break
23        r += step_r
24        c += step_c
25
26    return result

This version is useful when you want the visible diagonal path itself.

Handle Rectangular Matrices Too

The logic works for non-square matrices as long as both positions exist and the coordinates still satisfy the diagonal condition. Diagonal stepping does not require the matrix to be square.

What matters is:

  • rows have valid indices
  • columns have valid indices
  • the two points differ by equal row and column distance

Duplicate Values Need a Clear Rule

If the matrix contains repeated numbers, the question "between two numbers" becomes ambiguous. Possible interpretations are:

  • first occurrence of each value
  • nearest pair on a diagonal
  • all diagonal paths connecting matching values

Production code should define that rule explicitly instead of silently choosing the first match.

Complexity

Finding each value by scanning the matrix is O(rows * cols). Extracting the diagonal path afterward is only O(k), where k is the length of the diagonal segment.

If you need many such queries, precompute a map from value to position list so you do not rescan the matrix every time.

Common Pitfalls

  • Forgetting that equal row and column distance is required for a straight diagonal path.
  • Handling only the main diagonal and forgetting the anti-diagonal direction.
  • Returning values even when the two positions are not truly diagonal.
  • Ignoring duplicate values and accidentally using the wrong occurrence.
  • Mixing "between only" semantics with "include endpoints" semantics.

Summary

  • First locate both numbers in the matrix.
  • Two positions are diagonal if their row and column distance has the same absolute value.
  • Step by (+1, +1), (+1, -1), (-1, +1), or (-1, -1) to collect the path.
  • Decide whether the result should exclude or include the endpoints.
  • If matrix values are duplicated, define how the target positions should be chosen.

Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.