VOOZH about

URL: https://www.geeksforgeeks.org/dsa/swap-major-minor-diagonals-square-matrix/

⇱ Swap major and minor diagonals of a square matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Swap major and minor diagonals of a square matrix

Last Updated : 22 Jul, 2025

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

[Approach 1] Diagonal Buffer Swap - O(n) Time and O(n) Space

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.


Output
2 1 0 
3 4 5 
8 7 6 

[Approach 2] Two-Pointer Diagonal Swap - O(n) Time and O(1) Time

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.

👁 dsa_2

Output
2 1 0 
3 4 5 
8 7 6 
Comment
Article Tags: