Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Problem Statement
1.2.
Sample Examples
2.
Approach
2.1.
Pseudocode
2.2.
Implementation in C++
2.3.
Implementation in Java
2.3.1.
Time Complexity
2.3.2.
Space Complexity
3.
Frequently Asked Questions
3.1.
What are time and space complexity?
3.2.
What are the different types of matrix?
3.3.
What is a sparse matrix in data structure?
3.4.
What are the operations of matrix?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Swap upper diagonal elements with lower diagonal elements of matrix

Author Harsh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Data structure and algorithms is one of the most important topics if you want to crack the interview at a top product-based company. Having proper knowledge of DSA requires one to solve many coding problems. So, in this blog, we will discuss a coding problem in which we have to swap the upper and lower diagonal elements of a matrix. We’ll be using a 2d array to define the matrix.

Recommended Topic, Array Implementation of Queue and  Rabin Karp Algorithm

Problem Statement

Ninja has given you a square matrix of NxN dimension. You have to swap the lower diagonal elements with the upper diagonal elements and print the resultant matrix.

Sample Examples

Example 1

Input

Output

 

Explanation

 

 

Example 2

Input

 

Output

Explanation

Same as the previous example. We need to swap the lower diagonal elements with the upper diagonal elements.

Approach

As we have to swap the lower and upper diagonal elements. So, we’ll start traversing the array from the top left corner and we’ll keep track of the ith and jth location of the cell then as we proceed we’ll swap the element present at cell (i, j) with the element present at cell (j, i) until we reach at the end of the matrix.

Pseudocode

Algorithm SWAP_ELEMENTS(MAT)
for i <- 1 to n do
    for j <- i+1 to n do
        temp <- MAT[i][j]
        MAT[i][j] = MAT[j][i]
        MAT[j][i] = temp
    end
end

Implementation in C++

// C++ program to swap upper diagonal elements with
// lower diagonal elements
#include <bits/stdc++.h>
using namespace std;


// function to swap elements in the matrix
void swapElements(vector<vector<int>> matrix){


    // size of our matrix
    int n = matrix.size();


// swapping elements of matrix
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}

// printing the result
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << matrix[i][j] << " ";
cout << endl;
}


}


// main function
int main() {
    // getting the size of the matrix from user 
int n;
    cout << "Enter the size of the matrix: ";
    cin >> n;
    
    // input matrix;
    vector<vector<int>> matrix(n, vector<int>(n));


    // getting matrix elements from user
    cout << "Enter matrix elements: \n";
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            cin >> matrix[i][j];
        }
    }


// Function call
swapElements(matrix);


return 0;
}

Implementation in Java

// Java program to swap upper diagonal elements with
// lower diagonal elements
import java.util.Scanner;


class CodingNinja {

    // function to swap elements in the matrix
static void swapElements(int matrix[][]) {

        // size of our matrix
        int n = matrix.length;


        // swapping elements of matrix
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        
        // printing the result
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.print(matrix[i][j] + " ");
            System.out.println("");
        }

}

// main method
public static void main (String[] args) {


// getting matrix size from user
        System.out.print("Enter the size of the matrix: ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();


        // getting matrix elements from user
        int matrix[][] = new int[n][n];
        System.out.println("Enter matrix elements: ");
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                matrix[i][j] = sc.nextInt();
            }
        }


// Function call
swapElements(matrix);

}
}

 

Input

Enter the size of the matrix: 3
Enter matrix elements: 
1 2 3
6 5 4
7 9 8

 

Output

1 6 7 
2 5 9 
3 4 8 

Time Complexity

The time complexity for the above program is O(N^2) as we need to traverse the matrix to swap the elements.

Space Complexity

We are not using any extra space. So, the space complexity of our program is O(1).

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

Frequently Asked Questions

What are time and space complexity?

Time complexity refers to the time taken by the algorithm to complete its execution on the other hand space complexity refers to the amount of memory used by the algorithm while completing its execution.
 

What are the different types of matrix?

Row matrices, column matrices, null matrices, square matrices, diagonal matrices, upper triangular matrices, lower triangular matrices, symmetric matrices, and antisymmetric matrices are some of the several types of matrices.
 

What is a sparse matrix in data structure?

If the majority of the elements in a matrix are zero, it is called a sparse matrix. Another definition is a sparse matrix is a matrix having a maximum of 1/3 non-zero elements.
 

What are the operations of matrix?

The basic operations on the matrix are addition, subtraction, and multiplication. To add or subtract matrices, they must be in the same order, and for multiplication, the first matrix's number of columns must equal the second matrix's number of rows.

Conclusion

In this article, we have extensively discussed a coding problem where we have to swap the upper and lower diagonal elements of a matrix. We implemented the problem in two different programming languages.

We hope that this blog has helped you enhance your knowledge about the above question and if you would like to learn more, check out our articles Row-wise vs Column-wise Traversal of a MatrixFind Sum of all Elements in a Matrix except the Elements in Row and/or Column of Given CellBook Allocation ProblemStrassen’s Matrix Multiplication

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
Find Sum of all Elements in a Matrix except the Elements in Row and/or Column of Given Cell
Next article
Magic Square (Odd Order)
Live masterclass