Corner to Corner
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
Problem
You are given cells, a square matrix of integers from a tabular export flattened row by row into one list, and size, the matrix's side length. Return the values on the main diagonal, from the top-left corner to the bottom-right.
A grid pressed flat still remembers its corners.
Example 1
Input:
cells = [1,2,3,4,5,6,7,8,9], size = 3
Output:
[1,5,9]
Example 2
Input:
cells = [10,20,30,40], size = 2
Output:
[10,40]
Worked solution and explanation
What this is really testing
Under the matrix costume this is stride arithmetic, not a grid walk. The grid has already been pressed into one flat line, so there is no row-of-cells to iterate and no i == j to check: the values you want are simply the ones whose flat index is i*size + i. Candidates who see that write one line. Candidates who don't reach for cells[i] and hand back the first row, or scan the whole buffer hunting for diagonal values by content, which cannot work because a number carries no memory of where it sat. Get the stride wrong and a 1x1 buffer still passes by luck, so the mistake hides until a bigger matrix exposes it.
Where the diagonal went
Step 1: From (i, j) to a single offset
Row-major flattening lays row 0 first, then row 1, and so on. So the element at grid position (i, j) lands at flat index i*size + j. The main diagonal is every cell where the column equals the row, j equals i, which pins its flat index at i*size + i. That is the whole trick: one expression turns a 2-D coordinate into a 1-D offset.
Step 2: One counter, computed offset
One counter drives it. As i runs from 0 to size-1 you read cells[i*size + i] each time and never touch an off-diagonal element. Notice what is NOT available: iterating cells directly gives you a stream of integers with no way to tell a diagonal value from any other, so the side length is what makes the selection possible at all.
The solution
def extract_diagonal(cells, size):
return [cells[i * size + i] for i in range(size)]One offset per row, computed straight from the side length.
Common follow-up questions
- How would you pull the anti-diagonal, top-right to bottom-left, from the same flat buffer? (Tests flipping the offset to i*size + (size - 1 - i).)
- What changes if the buffer is a rows-by-cols rectangle instead of a square? (Tests generalizing the stride to a non-square shape, where the diagonal length is min(rows, cols) and the offset uses the column count as the width.)
- How would you return every diagonal running in the same direction, not just the main one? (Tests iterating over diagonal offsets: cells on one diagonal share a constant value of (col - row), so each offset shifts the starting column.)