![]() |
VOOZH | about |
Given a square matrix mat[][], swap the elements of its major and minor diagonals.
Major Diagonal (Primary/Main Diagonal): Elements that run from the top-left corner to the bottom-right corner of the matrix where the row and column indices are the same.
Minor Diagonal (Secondary Diagonal): Elements that run from the top-right corner to the bottom-left corner where the sum of row and column indices equals one less than the matrix size.
Examples:
Input: mat[][] = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]
Output :[[2, 1, 0],
[3, 4, 5],
[8, 7, 6]]
Explanation: Major Diagonal = [0, 4, 8], Minor Diagonal = [2, 4, 6]. We are required to swap the diagonal elements of same row, thus after doing so, major diagonal will become minor and vice-versa.Input: mat[][] = [[2, 3],
[5, 4]]
Output :[[3, 2],
[4, 5]]
Explanation: Major Diagonal = [2, 4], Minor Diagonal = [3, 5]. We are required to swap the diagonal elements of same row, thus after doing so, major diagonal will become minor and vice-versa
Table of Content
The idea is to store the elements of the major and minor diagonals separately to avoid overwriting, then swap them by placing each into the other's position.
2 1 0 3 4 5 8 7 6
In a square matrix, the major diagonal consists of elements where the row and column indices are equal (i.e., mat[i][i]), while the minor diagonal has elements where the sum of row and column indices equals one less than the matrix size (i.e., mat[i][mat.size() - 1 - i]).
To swap these diagonals, iterate through each row using a two-pointer like logic: one pointer accesses the major diagonal element, and the other accesses the minor diagonal element. Swap these elements in each row.
2 1 0 3 4 5 8 7 6