Back to questions
You are given an matrix. Your task is to determine if the matrix has diagonal stripes where all elements in each diagonal from top-left to bottom-right are of the same stripe—that is, they are identical.
In this context, each diagonal stripe runs from the top-left corner to the bottom-right corner of the matrix. Check if every diagonal stripe consists entirely of the same number.
Return if all diagonal stripes are of the same stripe, otherwise return .
Input: matrix =
Output:
Explanation:
In this grid, the diagonals are:
All elements in each diagonal ar identical. Thus, the answer is .
Input: matrix =
Output:
![Same Stripe DataLemur Example 2]
Explanation:
The diagonal does not consist of elements of the same stripe.
What if we could figure out which elements in a matrix are on the same diagonal stripe? This would make the problem easier. If we can group the elements on the same diagonal together, we could just check if all elements in each diagonal are equal.
But how do we determine if elements are on the same diagonal stripe? Let's use this example:
1 | 2 | 3 |
---|---|---|
4 | 5 | 6 |
7 | 8 | 9 |
10 | 11 | 12 |
We can use a dictionary to track diagonal elements efficiently. The key of the dictionary will be the difference , and the value will be the first element we encounter for that diagonal. Then, we'll compare subsequent elements on that diagonal to the stored value. If any mismatch is found, we return immediately. If we finish traversing the matrix without finding a mismatch, we return .
Here's how the approach works:
Here is the full code:
We can optimize the space by not storing the elements at all. Instead, we directly compare the current element with the previous element in the same diagonal. The previous element for any position would be (i.e., the element "northwest" of the current one). If the current element doesn't match the previous one, we return .
1 | 2 | 3 |
---|---|---|
4 | 5 | 6 |
7 | 8 | 9 |
10 | 11 | 12 |
Here is the full code: