Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem Statement
3.
Approach 1
3.1.
 
3.2.
C++ Code
3.3.
Output:  
3.4.
Java Code:
3.5.
Output:
4.
Time and Space Complexity
5.
Approach 2
5.1.
 
5.2.
C++ Code
5.3.
Output:
5.4.
Java Code
6.
Time and Space Complexity Analysis
7.
Frequently Asked Questions
7.1.
What is a matrix?
7.2.
What is the time complexity to traverse a 2D matrix?
7.3.
What is a vector?
7.4.
What is import?
7.5.
What is an object?
8.
Conclusion
Last Updated: Mar 27, 2024

Squares of Diagonals of a Matrix

Author Manish Kumar
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Hey Ninja !! Let’s dive into solving this easy yet interesting question involving matrix and its diagonals. We would cover all the aspects of the problem, from solution walkthrough to time and space complexity analysis. At the end of this blog, you will have in-depth knowledge of working with matrics. 

Also Read, Array Implementation of Queue and  Rabin Karp Algorithm

Problem Statement

You are given a square matrix of odd dimensions. Your task is to print the squares of both diagonal elements. Go through the examples to understand more.

Examples:

 

Input : 4 5 6 9         Output  : Diagonal One : 16 25 1 169

        8 5 9 12                         Diagonal Two : 81 81 16 1    

        7 4 1 3

        -1 2 8 13

 

Input : 5 6 7 8         Output  : Diagonal One : 25 100 9 81

        9 10 11 12                     Diagonal Two : 64 121 4 169

        1 2 3 4

        13 2 5 9

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Approach 1

Step 1: Initialise the matrix in the main function.

Step 2: Call the helper function, passing the matrix and its dimensions.

Step 3: Use a nested for loop to access each element and check whether its row index and

             column index are the same or not for the “diagonal one”.

Step 4: If it's the same print, it's square.

Step 5: For “diagonal two”, check if the sum of the row and column indices equals the number of columns minus one.

Step 6: If they are the same, print its square.

 

C++ Code

#include <bits/stdc++.h>

using namespace std;

//Helper function to calculate and print squares of diagonal elements
void helper(vector<vector<int>>&inputMatrix,int n)
{
    cout<<"Diagonal One : ";
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(i==j)
            {
                cout<<pow(inputMatrix[i][j],2)<<" ";
            }
        }
    }
    cout<<endl<<"Diagonal Two : ";
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(i+j==n-1)
            cout<<pow(inputMatrix[i][j],2)<<" ";
        }
    }
}
int main()
{   
  int n;
  //Taking side input from user
  cout<<"Enter the side length: ";
  cin>>n;
  
  vector<vector<int>>inputMatrix(n);
  
  cout<<"Enter the matrix elements:\n";
  
  //Taking matrix elements input
  for(int i=0;i<n;i++)
  {
      for(int j=0;j<n;j++)
      {    
          int x;
          cin>>x;
          inputMatrix[i].push_back(x);
      }
  }
  
  //Calling the helper function to calculate and print the elements
  helper(inputMatrix,n);
    return 0;
}

Output: 
 

 

Java Code:

import java.util.*;
public class Main
{
    //helper function to print the square of diagonal elements
    public static void helper(ArrayList<ArrayList<Integer>>inputMatrix,int n)
    {   
        //Code to print elements of Diagonal one
        System.out.print("Diagonal One : ");
            for(int i=0;i<n;i++)
                {
                for(int j=0;j<n;j++)
        {
            if(i==j)
            {
                System.out.print(inputMatrix.get(i).get(j)*inputMatrix.get(i).get(j) +"  ");
            }
        }
    }
    //Code to print elements of Diagonal two
System.out.print("\nDiagonal Two : ");
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(i+j==n-1)
            System.out.print(inputMatrix.get(i).get(j)*inputMatrix.get(i).get(j) +"  ");
        }
    }
    }
    
public static void main(String[] args) {
    
    //Taking side input from user
System.out.println("Enter the side length : ");
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();

//Initialising 2D matrix
ArrayList<ArrayList<Integer>>inputMatrix=new ArrayList<>(n);

//Taking matrix elements as input from user
for(int i=0;i<n;i++)
{   
    ArrayList<Integer>temp=new ArrayList();
    for(int j=0;j<n;j++)
    {
        int x=obj.nextInt();
        temp.add(x);
    }
    inputMatrix.add(temp);
}

helper(inputMatrix,n);
}
}

Output:

Time and Space Complexity

Time Complexity: O(N2)

Space Complexity: O(1)

Approach 2

Step 1: Initialise the matrix in the main function.

Step 2: Call the helper function, passing the matrix and its dimensions.

Step 3: For “diagonal one”, the logic is that we would use elements whose

        Both ‘i’ and ‘j’ values are the same. Use a for loop to achieve this functionality.

Step 4: Print the squares of each element.

Step 5: For the “diagonal two” the logic is inputMatrix[i][row-i-1] to capture each element.

Step 6: Print the squares of each element.

 

C++ Code

#include <bits/stdc++.h>

using namespace std;

//Helper function to calculate and print squares of diagonal elements
void helper(vector<vector<int>>&inputMatrix,int n)
{
    cout<<"Diagonal One : ";
    
    //Here output is found using single for loop
    for(int i=0;i<n;i++)
    {
      cout<<inputMatrix[i][i]*inputMatrix[i][i]<<"  ";
    }
    cout<<endl<<"Diagonal Two : ";
    
    //For loop for 2nd Diagonal elements square
    for(int i=0;i<n;i++)
    {
        cout<<inputMatrix[i][n-i-1]*inputMatrix[i][n-i-1]<<"  ";
    }
}
int main()
{   
  int n;
  //Taking side input from user
  cout<<"Enter the side length: ";
  cin>>n;
  
  vector<vector<int>>inputMatrix(n);
  
  cout<<"Enter the matrix elements:\n";
  
  //Taking matrix elements input
  for(int i=0;i<n;i++)
  {
      for(int j=0;j<n;j++)
      {    
          int x;
          cin>>x;
          inputMatrix[i].push_back(x);
      }
  }
  
  //Calling the helper function to calculate and print the elements
  helper(inputMatrix,n);
    return 0;
}

Output:

Java Code

import java.util.*;
public class Main
{
    //helper function to print the square of diagonal elements
    public static void helper(ArrayList<ArrayList<Integer>>inputMatrix,int n)
    {   
        //Code to print elements of Diagonal one
        System.out.print("Diagonal One : ");
            for(int i=0;i<n;i++)
                {
                    System.out.print(inputMatrix.get(i).get(i)*inputMatrix.get(i).get(i)+"  ");
                }
        //Code to print elements of Diagonal two
        System.out.print("\nDiagonal Two : ");
        for(int i=0;i<n;i++)
        {
            System.out.print(inputMatrix.get(i).get(n-i-1)*inputMatrix.get(i).get(n-i-1)+"  ");
        }
    }
    
public static void main(String[] args) {
    
    //Taking side input from user
System.out.println("Enter the side length : ");
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();

//Initialising 2D matrix
ArrayList<ArrayList<Integer>>inputMatrix=new ArrayList<>(n);

//Taking matrix elements as input from user
for(int i=0;i<n;i++)
{   
    ArrayList<Integer>temp=new ArrayList();
    for(int j=0;j<n;j++)
    {
        int x=obj.nextInt();
        temp.add(x);
    }
    inputMatrix.add(temp);
}

helper(inputMatrix,n);
}
}

  Output:

Time and Space Complexity Analysis

  • Let “n” be the one side dimension of the matrix.
  • Only “n” number of traversals are made for one diagonal.
  • Therefore total time taken is n+n, i.e. 2n
  • In big O notation, it is O(n)
  • No extra space is used for diagonal elements’ square calculation.
  • Therefore space complexity is O(1)

 

Time complexity: O(n)

Space complexity: O(1)

Must Read Difference between ArrayList and LinkedList

Frequently Asked Questions

What is a matrix?

A matrix is an array of arrays. You can consider it as a grid.

What is the time complexity to traverse a 2D matrix?

The time taken is O(n*n).

What is a vector?

A vector is a data structure which allows dynamic-sized arrays, i.e. array size can change at runtime. 

What is import?

This is a keyword in java which is used to import pre-written libraries.

What is an object?

An object is an instance of a class.

Conclusion

This blog taught you how to deal with 2-D matrices and access their diagonals. You can use this knowledge to solve other questions based on matrix diagonals. You also learned how to analyse time and space complexity.

If you want to go through more questions like this, follow this link: 2-D matrix problemsPrint diagonalDiagonal Traverse IIMirror Diagonals

Recommended Readings:

 

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enrol in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

 

 

Please do upvote our blogs if you find them helpful and informative!

Happy learning!

Previous article
Kronecker Product of Two Matrices
Next article
Program to Check Involutory Matrix
Live masterclass