Skip to content
DeepForgeby svx
All problems
MediumLinear Algebrala-119

k-th Diagonal Extraction

Problem

Extract the k-th diagonal of a square matrix A.

k = 0 is the main diagonal, k > 0 is above it (entries A[i][i + k]), and k < 0 is below it (entries A[i][i + k]). Return the entries in order.

Hint

Slide the diagonal by k columns; only indices inside the matrix count.

Test cases

case 1
in: [[[1,2,3],[4,5,6],[7,8,9]],1]
expected: [2,6]
case 2
in: [[[1,2,3],[4,5,6],[7,8,9]],-1]
expected: [4,8]
case 3
in: [[[1,2,3],[4,5,6],[7,8,9]],2]
expected: [3]
case 4
in: [[[1,2,3],[4,5,6],[7,8,9]],0]
expected: [1,5,9]
Starter codePython
def diagonal_k(A, k):
    # Your code here
    pass

4 test cases · run your code against them in the editor