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.
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.
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.
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.
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
- How to get dot product of two sparsevectors in Omn , where m and n are the number of elements in both vectors
- How to get largest number of consecutive integers in a substantially large array (spread across multiple machines)
- how to get longest repeating string in substring from suffix tree
- how to get started with TopCoder to update/develop algorithm skills?
- How to get the cut-set using the Edmonds–Karp algorithm?
- How to get the iterator for a successful binary_search?
- How to get the K smallest Products from pairs from two sorted Arrays?
- How to get the smallest in lexicographical order?

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 courseTrack 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.