In this article
Before you start
This page is one step of the coding interview learning path.
Why interviewers ask this
Comparing two grids looks trivial, which is why it shows up as a warm-up or as a hidden step inside a larger problem. The consequence of a careless answer is a wrong result on a case the candidate never tried: two matrices of different shape, a matrix of decimals, or an empty matrix. Interviewers use it to see whether a candidate states the rule before coding, handles the cheap check (shape) before the expensive one (entries), and can say what the cost is.
A weak answer loops over entries and assumes both inputs have the same shape. A strong answer checks the shape first, stops at the first mismatch and states the cost. A Staff-level answer also explains why exact comparison is wrong for decimal data and what to use instead. Textbooks usually call this equality of matrices; this page reads "identical matrices" as equal matrices, and separates it from the identity matrix, which people often confuse it with.
Identical matrices from first principles
- Identical matrices
- Identical matrices are two matrices that have the same order and an equal value in every pair of corresponding positions, so one can replace the other in any calculation without changing the result. The textbook name for this rule is equality of matrices.
- Order of a matrix
- The order of a matrix is its size written as rows by columns, so a matrix with two rows and three columns has order 2 by 3. Two matrices can only be equal if their orders are equal.
In plain words
Picture two spreadsheet grids. They are the same if both have the same number of rows and columns. Every cell must also hold the same number. One different cell makes them different. The analogy breaks in one place: a matrix has no colours or labels, only the numbers and the shape. So a grid with the same numbers laid out in a different shape is a different matrix.
In one precise sentence, matrices A and B are identical when the order of A equals the order of B and, for every row i and column j, the entry A(i, j) equals B(i, j).1
The checking procedure has four steps. Each is one stage in the figure below.
Step 1: Compare the order first
Two matrices of different order are never identical, so the first check is the shape. A 2 by 2 matrix and a 2 by 3 matrix cannot be equal, whatever numbers they hold, because the second has two extra positions that the first does not have.2 The same-order requirement is part of the standard rule of equality of matrices.
Input: the two row counts and the two column counts. Output: stop with "not equal" if either pair differs, otherwise continue. This check costs a fixed handful of comparisons however large the matrices are, which is why it comes first: a mismatch here saves reading any entry. You now know the cheap gate; the next step is the expensive scan.
Step 2: Compare entries, and what A == B really returns
An element-wise comparison is a comparison that pairs the entry at each position of one matrix with the entry at the same position of the other and tests each pair separately. In plain Python you write two loops over rows and columns. For lists of lists, A == B compares lengths and then entries in order, stops at the first difference and returns one value (Python reference, value comparisons).
NumPy is a third-party Python package for numerical arrays, and there the operator A == B is element-wise: it returns a whole grid of true and false values, not one answer. Using that grid in an if raises an error for any grid with more than one entry. To get one answer, use undefined, which returns true only when both arrays have the same shape and equal elements, or call .all() on the result of A == B after confirming the shapes match.
Step 3: Stop at the first mismatch
The scan can return "not equal" as soon as it finds one differing pair, so it rarely reads every entry unless the matrices are equal. In the worked example, a matrix that differs from the original in the top-right entry is rejected after two comparisons, not four.2
The worst case happens when the matrices are equal, or differ only at the very last position. Then every entry is read once, which is rows times columns checks, written O(m·n) for m rows and n columns. Like the single left-to-right pass of the sliding window solution for the longest substring without repeating characters, the entry scan reads each position a constant number of times, here exactly once.
Step 4: Use a tolerance for decimal numbers
A tolerance is the largest difference between two numbers that you still treat as equal. Decimal numbers need one because computers store most decimals in binary, so results of arithmetic carry tiny rounding errors.
In Python, adding one tenth and two tenths gives a value just above three tenths, so an exact equality test against three tenths is false, even though the two values agree to many digits; Python's floating-point tutorial explains the binary storage behind this.2 undefined handles this by treating two numbers as equal when the absolute difference is at most an absolute tolerance plus a relative tolerance times the size of the second number, with defaults of 1e-05 for the relative part and 1e-08 for the absolute part. Technically, that makes the matrices close, not identical; choose it only for measured or computed decimals, never for integers.
Step-by-step description
- Different order means not equal.
- Compare each pair of entries.
- The first failing pair means not equal.
- Decimals use a tolerance; all pairs passing means equal.
- Matrices with different order are never equal.
- Entries are compared pair by pair.
- The scan stops at the first mismatch.
- Decimal matrices need a tolerance instead of exact equality.
Knowing it is half the job. Saying it is the other half.
Interview Clozo is an AI interview copilot for real interview rounds: it hears the question and puts a strong answer on your screen, and you say it in your own words. See the features or how it works.
Start Free Trial →Worked example
Here is the procedure run on small matrices, with real output from a short script. Let A be the matrix with rows (1, 2) and (3, 4), and B an exact copy of it. The check finds equal orders, then compares four pairs, all equal, so A and B are identical after four entry checks.2
Now vary one thing at a time. Matrix W has rows (1, 2, 5) and (3, 4, 6): the order differs, so the answer is "not equal" after zero entry checks. Matrix T, the transpose of A (rows and columns swapped), has rows (1, 3) and (2, 4): the same entries in a different arrangement, and the check stops at the second pair, 2 against 3. Matrix C has rows (1, 9) and (3, 4) and also stops at the second pair.2
| Case | Result | Entry checks |
|---|---|---|
| A against an exact copy B | equal | 4 |
| A (2 by 2) against W (2 by 3) | not equal | 0 |
| A against its transpose T | not equal | 2 |
| A against C (top-right entry changed) | not equal | 2 |
| A against the identity matrix of order 2 | not equal | 2 |
| Worst case, 2 by 3 matrices | at most | 6 |
| Worst case, 1,000 by 1,000 matrices | at most | 1,000,000 |
The cost grows with the number of entries, so doubling the side of a square matrix quadruples the worst case: 4 checks for a 2 by 2 matrix, 16 for 4 by 4, 64 for 8 by 8 and 256 for 16 by 16.2
Text description of the diagram
- A 2 by 2 matrix needs at most 4 entry checks.
- A 16 by 16 matrix needs at most 256 entry checks.
- Doubling the side of a square matrix quadruples the worst case.
For decimals, take a matrix whose first entry is the computed sum 0.1 plus 0.2, and another with 0.3 in that place, all other entries equal. The exact comparison fails at the first pair. The tolerance comparison passes, because the difference of about 5.55e-17 is far below the bound of 3.01e-06 that the defaults give at the value 0.3.2
A short version of the whole procedure:
def identical(A, B):
# Step 1: orders must match (same rows, same columns)
if len(A) != len(B) or any(len(a) != len(b) for a, b in zip(A, B)):
return False
# Steps 2 and 3: compare entry by entry, stop at the first mismatch
for row_a, row_b in zip(A, B):
for x, y in zip(row_a, row_b):
if x != y:
return False
return TrueThe function reads two lists of lists. The first if is the shape gate, the loops are the entry scan, and return False inside the loop is the early exit. For decimal data replace x != y with abs(x - y) > tolerance, where tolerance is a number you choose. The same two-loop logic carries over unchanged to C, C++ and Java; in C++, == on two std::vector<std::vector<int>> objects compares sizes and then elements, much like the Python list comparison.
Trade-offs and edge cases
Exact equality is right for integers, booleans and labels, and wrong for measured or computed decimals. Tolerance equality is right for those decimals but is no longer an equivalence in the strict sense: close is not transitive, because A can be close to B and B close to C while A and C are not close. NumPy also states that allclose(a, b) can differ from allclose(b, a), because the relative part of the bound uses the second argument.
In recent NumPy versions, A == B on shapes that cannot be stretched to match raises an error instead of returning false, which is one more reason to check the order first. The .all() shortcut is safe only after that check: NumPy may stretch a smaller array to fit a larger one, so a mismatched shape can otherwise slip through.
Text description of the diagram
- Equal matrices have the same order and the same entries.
- The identity matrix has ones on the diagonal and zeros elsewhere.
- Matrices of the same order may still differ in their entries.
Edge cases to name aloud:
- Identity is a different idea. The identity matrix is a square matrix with ones on the diagonal and zeros elsewhere. It is a single fixed matrix for each size, while identical matrices describe a relationship between two matrices. A matrix equals the identity only when it has exactly that pattern.
- Not-a-number values. A not-a-number value (NaN) is not equal to itself under
==, so a matrix containing one is never exact-equal to its own copy; NumPy'sarray_equalhas an option to treat them as equal. - Integer against float. In Python the integer 1 equals the float 1.0, so matrices of different number types can still compare equal entry by entry.
- Empty matrices. Say which representation you mean: in Python,
[]has no rows and[[]]has one row with no columns. Two empty matrices of the same representation have nothing to compare and are equal by the rule, while[]against[[]]differ in order. - Same entries, different order. Rearranging entries, or reshaping them, produces a different matrix, as the transpose case above shows.
For counting how many positions differ rather than stopping at the first, the idea is the one in Hamming distance, applied to grids. Python details that often come up alongside this question are collected in Python interview questions and answers.
How to answer it in an interview
How would you check whether two matrices are identical?
Identical matrices are equal matrices: the same order, and equal entries in every matching position. In code I first compare the shapes, because different shapes can never be equal and that check costs almost nothing. Then I scan entry by entry and return false at the first mismatch, so the worst case reads every entry, which is rows times columns. For decimal data I would not use exact equality, because a tenth plus two tenths is not exactly three tenths in binary arithmetic. I would compare with a tolerance instead.
The spoken structure: say the rule, do the cheap shape check, scan with early exit, state the cost, then raise the decimal caveat before the interviewer does.
Common mistakes
- "I loop over the entries of the first matrix and compare with the second." (wrong) This crashes or reads out of range when the second matrix is smaller, and wrongly passes when it is larger and shares a prefix. (right) "I compare the orders first, then loop."
- "In NumPy,
if A == B:tells me if they are equal." (wrong) The operator returns a grid of true and false values, and using it in anifraises an error for grids with more than one entry. (right) "I usenumpy.array_equal, or I check the shape and then call.all()." - "The identity matrix and identical matrices are the same thing." (wrong) One is a fixed matrix, the other is a relationship between two matrices. (right) "Two matrices can be identical without being identity matrices."
- "I compare decimals with
==because it is exact." (wrong) Rounding error makes 0.1 plus 0.2 differ from 0.3. (right) "I compare with an absolute or relative tolerance." - "The matrices hold the same numbers, so they are equal." (wrong) Position and shape matter. (right) "Same order and same value at each position."
Follow-up questions
What is the difference between identical matrices and the identity matrix?
Identical matrices are any two matrices with the same order and equal entries. The identity matrix is one specific square matrix, with ones on the diagonal and zeros elsewhere, which leaves other matrices unchanged when multiplied by them.
Are two matrices with the same entries in a different order equal?
No. Equality needs the same value at every matching position, so a rearranged matrix or a different shape is a different matrix, even when it holds exactly the same numbers.
How do you compare two matrices in Python?
For lists of lists, A == B returns a single true or false value and already checks shape and entries. For NumPy arrays use numpy.array_equal (exact) or numpy.allclose (tolerance).
What is the time complexity of checking whether two matrices are equal?
The worst case is O(m·n) for m rows and n columns, because every entry may be read once. The best case is constant time when the shapes differ, and an early mismatch returns sooner than the worst case.
How do you compare two matrices that hold decimal numbers?
Compare with a tolerance rather than ==, for example the NumPy defaults of 1e-05 relative and 1e-08 absolute, and choose values that match the precision of your data.
What if the matrices are 1,000 by 1,000?
The worst case is still O(m·n), which is one million entry checks here,2 and you cannot do better for an exact answer, because any unread entry could differ. If many pairs must be compared repeatedly, store a hash (fingerprint) of each matrix and compare the hashes first, then run the full entry check when the hashes match, because collisions are possible; the hashing and array fundamentals ladder covers hashing in more depth. In NumPy, use the vectorised array_equal rather than Python loops. More practice is in coding interview questions.
- Identical matrices have the same order and equal entries in every matching position.
- Check the shape first, then scan entries and stop at the first mismatch.
- The worst case is rows times columns entry checks, so doubling the side quadruples it.
A == Bin NumPy returns a grid; usenumpy.array_equalfor one answer.- Compare decimals with a tolerance; identical and identity are different ideas.
Sources
- Equality of Matrices: Rules and Examples — Bhanzu (tutoring site; undated page, accessed 2026-10-26), 26 Oct 2026
- Python language reference: value comparisons — Python documentation (accessed 2026-10-26), 26 Oct 2026
- Floating-point arithmetic: issues and limitations, Python tutorial — Python documentation (accessed 2026-10-26), 26 Oct 2026
- numpy.array_equal, NumPy v2.5 Manual — NumPy documentation, 28 Jun 2026
- numpy.allclose, NumPy v2.5 Manual — NumPy documentation, 28 Jun 2026