Kth diagonal from the top left of a given matrix

Given a squared matrix M[ ][ ] of N * N dimensions, the task is to find the Kth diagonal of the matrix, starting from the top-left towards the bottom-right, and print its contents.
Examples: 
 

Input: N = 3, K = 2, M[ ][ ] = {{4, 7, 8}, {9, 2, 3}, {0, 4, 1} 
Output: 9 7 
Explanation: 
5 possible diagonals starting from the top left to the bottom right for the given matrix are: 
1 -> {4} 
2 -> {9, 7} 
3 -> {0, 2, 8} 
4 -> {4, 3} 
5 -> {1} 
Since K = 2, the required diagonal is (9, 7).
Input: N = 2, K = 2, M[ ][ ] = {1, 5}, {9, 4}} 
Output:
Explanation: 
3 possible diagonals starting from the bottom left to the top right for the given matrix are: 
1 -> {1} 
2 -> {9, 5} 
3 -> {4} 
Since K = 2, the required diagonal is (9, 5). 
 

Naive Approach: 
The simplest approach to solve this problem is to generate all diagonals starting from the top-left to the bottom right of the given matrix. After generating the Kth diagonal, print its contents. 
Time complexity: O(N2
Auxiliary Space: O(N)
Efficient Approach: 
The above approach can be optimized by avoiding the traversal of the matrix. Instead, find the boundaries of the Kth diagonal i.e. bottom-left and top-right indices. Once these indices are obtained, print the required diagonal by just traversing the indices of the diagonal. 
The following observations are needed to find the position of the diagonal: 
 

If ((K – 1) < N): The diagonal is an upper diagonal 
Bottom-left boundary = M[K – 1][0] 
Top-right boundary = M[0][K – 1]
If (K ? N): The diagonal is a lower diagonal. 
Bottom-left boundary = M[N-1][K-N] 
Top-right boundary = M[K-N][N-1] 
 

Follow the steps below to solve the problem: 
 



  • If (K – 1) < N, set the starting row, startRow as K – 1 and column, startCol as 0.
  • Otherwise, set startRow as N – 1 and startCol as K – N.
  • Finally, print the elements of diagonal starting from M[startRow][startCol].

Below is the implementation of the above approach: 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function returns required diagonal
void printDiagonal(int K, int N,
                vector<vector<int> >& M)
{
    int startrow, startcol;
 
    // Initialize values to
    // print upper diagonals
    if (K - 1 < N) {
        startrow = K - 1;
        startcol = 0;
    }
 
    // Initialize values to
    // print lower diagonals
    else {
        startrow = N - 1;
        startcol = K - N;
    }
 
    // Traverse the diagonal
    for (; startrow >= 0 && startcol < N;
        startrow--, startcol++) {
 
        // Print its contents
        cout << M[startrow][startcol]
            << " ";
    }
}
 
// Driver Code
int main()
{
    int N = 3, K = 4;
    vector<vector<int> > M = { { 4, 7, 8 },
                            { 9, 2, 3 },
                            { 0, 4, 1 } };
 
    printDiagonal(K, N, M);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of
// the above approach
import java.util.*;
 
class GFG{
 
// Function returns required diagonal
static void printDiagonal(int K, int N,
                          int [][]M)
{
    int startrow, startcol;
 
    // Initialize values to
    // print upper diagonals
    if (K - 1 < N)
    {
        startrow = K - 1;
        startcol = 0;
    }
 
    // Initialize values to
    // print lower diagonals
    else
    {
        startrow = N - 1;
        startcol = K - N;
    }
 
    // Traverse the diagonal
    for(; startrow >= 0 && startcol < N;
          startrow--, startcol++)
    {
         
        // Print its contents
        System.out.print(M[startrow][startcol] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 3, K = 4;
    int[][] M = { { 4, 7, 8 },
                  { 9, 2, 3 },
                  { 0, 4, 1 } };
 
    printDiagonal(K, N, M);
}
}
 
// This code is contributed by PrinciRaj1992

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the
# above approach
def printDiagonal(K, N, M):
     
    startrow, startcol = 0, 0
 
    # Initialize values to prupper
    # diagonals
    if K - 1 < N:
        startrow = K - 1
        startcol = 0
    else:
        startrow = N - 1
        startcol = K - N
 
    # Traverse the diagonals
    while startrow >= 0 and startcol < N:
         
        # Print its contents
        print(M[startrow][startcol], end = " ")
        startrow -= 1
        startcol += 1
 
# Driver code
if __name__ == '__main__':
     
    N, K = 3, 4
    M = [ [ 4, 7, 8 ],
          [ 9, 2, 3 ],
          [ 0, 4, 1 ] ]
           
    printDiagonal(K, N, M)
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of
// the above approach
using System;
class GFG{
 
// Function returns required diagonal
static void printDiagonal(int K, int N,
                          int [,]M)
{
    int startrow, startcol;
 
    // Initialize values to
    // print upper diagonals
    if (K - 1 < N)
    {
        startrow = K - 1;
        startcol = 0;
    }
 
    // Initialize values to
    // print lower diagonals
    else
    {
        startrow = N - 1;
        startcol = K - N;
    }
 
    // Traverse the diagonal
    for(; startrow >= 0 && startcol < N;
          startrow--, startcol++)
    {
         
        // Print its contents
        Console.Write(M[startrow,startcol] + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 3, K = 4;
    int[,] M = { { 4, 7, 8 },
                 { 9, 2, 3 },
                 { 0, 4, 1 } };
 
    printDiagonal(K, N, M);
}
}
 
// This code is contributed by PrinciRaj1992

chevron_right


Output: 
 

4 3 


Time complexity: O(N) 
Auxiliary Space: O(1)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.