Inplace (Fixed space) M x N size matrix transpose
Last Updated : 15 Aug, 2023
Given an M x N matrix, transpose the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array. If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D array across it's diagonal (try yourself). How to transpose an arbitrary size matrix inplace? See the following matrix,
a b c a d g j d e f ==> b e h k g h i c f i l j k l
As per 2D numbering in C/C++, corresponding location mapping looks like,
Org element New 0 a 0 1 b 4 2 c 8 3 d 1 4 e 5 5 f 9 6 g 2 7 h 6 8 i 10 9 j 3 10 k 7 11 l 11
Note that the first and last elements stay in their original location. We can easily see the transformation forms few permutation cycles.
- 1->4->5->9->3->1 - Total 5 elements form the cycle
- 2->8->10->7->6->2 - Another 5 elements form the cycle
- 0 - Self cycle
- 11 - Self cycle
From the above example, we can easily devise an algorithm to move the elements along these cycles. How can we generate permutation cycles? Number of elements in both the matrices are constant, given by N = R * C, where R is row count and C is column count. An element at location ol (old location in R x C matrix), moved to nl (new location in C x R matrix). We need to establish relation between ol, nl, R and C. Assume ol = A[or][oc]. In C/C++ we can calculate the element address as,
ol = or x C + oc (ignore base reference for simplicity)
It is to be moved to new location nl in the transposed matrix, say nl = A[nr][nc], or in C/C++ terms
nl = nr x R + nc (R - column count, C is row count as the matrix is transposed)
Observe, nr = oc and nc = or, so replacing these for nl,
nl = oc x R + or -----> [eq 1]
after solving for relation between ol and nl, we get
ol = or x C + oc ol x R = or x C x R + oc x R = or x N + oc x R (from the fact R * C = N) = or x N + (nl - or) --- from [eq 1] = or x (N-1) + nl
OR,
nl = ol x R - or x (N-1)
Note that the values of nl and ol never go beyond N-1, so considering modulo division on both the sides by (N-1), we get the following based on properties of congruence,
nl mod (N-1) = (ol x R - or x (N-1)) mod (N-1) = (ol x R) mod (N-1) - or x (N-1) mod(N-1) = ol x R mod (N-1), since second term evaluates to zero nl = (ol x R) mod (N-1), since nl is always less than N-1
A curious reader might have observed the significance of above relation. Every location is scaled by a factor of R (row size). It is obvious from the matrix that every location is displaced by scaled factor of R. The actual multiplier depends on congruence class of (N-1), i.e. the multiplier can be both -ve and +ve value of the congruent class.Hence every location transformation is simple modulo division. These modulo divisions form cyclic permutations. We need some book keeping information to keep track of already moved elements. Here is code for inplace matrix transformation,
Implementation:
C++ // C++ program for in-place matrix transpose #include <bits/stdc++.h> #define HASH_SIZE 128 using namespace std; // A utility function to print a 2D array // of size nr x nc and base address A void Print2DArray(int *A, int nr, int nc) { for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) { cout<<setw(4)<<*(A + r*nc + c); } cout<<endl; } cout<<endl; } // Non-square matrix transpose of // matrix of size r x c and base address A void MatrixInplaceTranspose(int *A, int r, int c) { int size = r*c - 1; int t; // holds element to be replaced, // eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix [c x r] // i_new = (i*r)%(N-1) next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while (i != cycleBegin); // Get Next Move (what about querying random location?) for (i = 1; i < size && b[i]; i++) ; cout << endl; } } // Driver program to test above function int main() { int r = 5, c = 6; int size = r*c; int *A = new int[size]; for(int i = 0; i < size; i++) A[i] = i+1; Print2DArray(A, r, c); MatrixInplaceTranspose(A, r, c); Print2DArray(A, c, r); delete[] A; return 0; } // This code is contributed by rrrtnx.
C // Program for in-place matrix transpose #include <stdio.h> #include <iostream> #include <bitset> #define HASH_SIZE 128 using namespace std; // A utility function to print a 2D array of size nr x nc and base address A void Print2DArray(int *A, int nr, int nc) { for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) printf("%4d", *(A + r*nc + c)); printf("\n"); } printf("\n\n"); } // Non-square matrix transpose of matrix of size r x c and base address A void MatrixInplaceTranspose(int *A, int r, int c) { int size = r*c - 1; int t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix [c x r] // i_new = (i*r)%(N-1) next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while (i != cycleBegin); // Get Next Move (what about querying random location?) for (i = 1; i < size && b[i]; i++) ; cout << endl; } } // Driver program to test above function int main(void) { int r = 5, c = 6; int size = r*c; int *A = new int[size]; for(int i = 0; i < size; i++) A[i] = i+1; Print2DArray(A, r, c); MatrixInplaceTranspose(A, r, c); Print2DArray(A, c, r); delete[] A; return 0; }
Java // Java program for in-place matrix transpose import java.util.*; class gfg { static int HASH_SIZE = 128; // A utility function to pr a 2D array // of size nr x nc and base address A static void Pr2DArray(int[] A, int nr, int nc) { for (int r = 0; r < nr; r++) { for (int c = 0; c < nc; c++) { System.out.print(String.format( "%1$" + 4 + "s", (A[r * nc + c] + ""))); } System.out.println(); } System.out.println(); } // Non-square matrix transpose of // matrix of size r x c and base address A static int[] MatrixInplaceTranspose(int[] A, int r, int c) { int size = r * c - 1; int t; // holds element to be replaced, // eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator int b = 1; // hash to mark moved elements b |= (1 << size); i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%(N-1) next = (i * r) % size; int temp = A[next]; A[next] = t; t = temp; b |= (1 << i); i = next; } while (i != cycleBegin); // Get Next Move (what about querying random // location?) for (i = 1; i < size && ((b & (1 << i)) != 0); i++) ; System.out.println(); } return A; } // Driver program to test above function public static void main(String[] args) { int r = 5, c = 6; int size = r * c; int[] A = new int[size]; for (int i = 0; i < size; i++) A[i] = i + 1; Pr2DArray(A, r, c); A = MatrixInplaceTranspose(A, r, c); Pr2DArray(A, c, r); } } // This code is contributed by karandeep1234
Python3 # Python3 program for in-place matrix transpose HASH_SIZE = 128 # A utility function to pr a 2D array # of size nr x nc and base address A def Pr2DArray( A, nr, nc): for r in range(nr): for c in range(nc): print('{0: >4}'.format(str(A[r * nc + c])), end = "") print() print() # Non-square matrix transpose of # matrix of size r x c and base address A def MatrixInplaceTranspose( A, r, c): size = r * c - 1; b = 1; # hash to mark moved elements b |= (1 << size); i = 1; # Note that A[0] and A[size-1] won't move while (i < size): cycleBegin = i; t = A[i]; while True: # Input matrix [r x c] # Output matrix [c x r] # i_new = (i*r)%(N-1) next1 = (i*r)%size; temp = A[next1] A[next1] = t t = temp b |= (1 << i) i = next1; if i == cycleBegin: break # Get next1 Move (what about querying random location?) i = 1 while i < size and ( (b & (1 << i)) != 0): i += 1 print() return A # Driver program to test above function r = 5 c = 6; size = r*c; A = [i + 1 for i in range(size)] Pr2DArray(A, r, c); A = MatrixInplaceTranspose(A, r, c); Pr2DArray(A, c, r); # This code is contributed by phasing17.
C# // C# program for in-place matrix transpose using System; using System.Collections.Generic; class GFg { static int HASH_SIZE = 128; // A utility function to pr a 2D array // of size nr x nc and base address A static void Pr2DArray(int[] A, int nr, int nc) { for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) { Console.Write(Convert.ToString(A[r * nc + c]).PadLeft(4)); } Console.WriteLine(); } Console.WriteLine(); } // Non-square matrix transpose of // matrix of size r x c and base address A static int[] MatrixInplaceTranspose(int[] A, int r, int c) { int size = r * c - 1; int t; // holds element to be replaced, // eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator int b = 1; // hash to mark moved elements b |= (1 << size); i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix [c x r] // i_new = (i*r)%(N-1) next = (i*r)%size; int temp = A[next]; A[next] = t; t = temp; b |= (1 << i); i = next; } while (i != cycleBegin); // Get Next Move (what about querying random location?) for (i = 1; i < size && ( (b & (1 << i)) != 0); i++) ; Console.WriteLine(); } return A; } // Driver program to test above function public static void Main(string[] args) { int r = 5, c = 6; int size = r*c; int[] A = new int[size]; for(int i = 0; i < size; i++) A[i] = i+1; Pr2DArray(A, r, c); A = MatrixInplaceTranspose(A, r, c); Pr2DArray(A, c, r); } } // This code is contributed by phasing17.
JavaScript // JS program for in-place matrix transpose let HASH_SIZE = 128 // A utility function to pr a 2D array // of size nr x nc and base address A function Pr2DArray( A, nr, nc) { for(let r = 0; r < nr; r++) { for(let c = 0; c < nc; c++) { process.stdout.write((A[r * nc + c].toString()).padStart(4)) } console.log() } console.log() } // Non-square matrix transpose of // matrix of size r x c and base address A function MatrixInplaceTranspose( A, r, c) { let size = r * c - 1; let t; // holds element to be replaced, // eventually becomes next element to move let next; // location of 't' to be moved let cycleBegin; // holds start of cycle let i; // iterator let b = 1; // hash to mark moved elements b |= (1 << size); i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix [c x r] // i_new = (i*r)%(N-1) next = (i*r)%size; let temp = A[next] A[next] = t t = temp b |= (1 << i) i = next; } while (i != cycleBegin); // Get Next Move (what about querying random location?) for (i = 1; i < size && ( (b & (1 << i)) != 0); i++) ; console.log() } return A } // Driver program to test above function let r = 5, c = 6; let size = r*c; let A = new Array(size); for( i = 0; i < size; i++) A[i] = i+1; Pr2DArray(A, r, c); A = MatrixInplaceTranspose(A, r, c); Pr2DArray(A, c, r); // This code is contributed by phasing17.
Output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 1 7 13 19 25 2 8 14 20 26 3 9 15 21 27 4 10 16 22 28 5 11 17 23 29 6 12 18 24 30
Time Complexity: O(R*C), here R & C are number number of Rows and Columns respectively.
Auxiliary Space : O(size of the bitset)
Extension: 17 - March - 2013 Some readers identified similarity between the matrix transpose and string transformation. Without much theory I am presenting the problem and solution. In given array of elements like [a1b2c3d4e5f6g7h8i9j1k2l3m4]. Convert it to [abcdefghijklm1234567891234]. The program should run inplace. What we need is an inplace transpose. Given below is code.
Implementation:
C++ #include <bits/stdc++.h> #define HASH_SIZE 128 using namespace std; typedef char data_t; void Print2DArray(char A[], int nr, int nc) { int size = nr*nc; for(int i = 0; i < size; i++) cout<<setw(4)<<*(A+i); cout<<endl; } void MatrixTransposeInplaceArrangement(data_t A[], int r, int c) { int size = r*c - 1; data_t t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while( i < size ) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix [c x r] // i_new = (i*r)%size next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while( i != cycleBegin ); // Get Next Move (what about querying random location?) for(i = 1; i < size && b[i]; i++) ; cout << endl; } } void Fill(data_t buf[], int size) { // Fill abcd ... for(int i = 0; i < size; i++) buf[i] = 'a'+i; // Fill 0123 ... buf += size; for(int i = 0; i < size; i++) buf[i] = '0'+i; } void TestCase_01(void) { int r = 2, c = 10; int size = r*c; data_t *A = new data_t[size]; Fill(A, c); Print2DArray(A, r, c), cout << endl; MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r), cout << endl; delete[] A; } int main() { TestCase_01(); return 0; } // This code is contributed by rutvik_56.
C #include <stdio.h> #include <iostream> #include <bitset> #define HASH_SIZE 128 using namespace std; typedef char data_t; void Print2DArray(char A[], int nr, int nc) { int size = nr*nc; for(int i = 0; i < size; i++) printf("%4c", *(A + i)); printf("\n"); } void MatrixTransposeInplaceArrangement(data_t A[], int r, int c) { int size = r*c - 1; data_t t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while( i < size ) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix [c x r] // i_new = (i*r)%size next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while( i != cycleBegin ); // Get Next Move (what about querying random location?) for(i = 1; i < size && b[i]; i++) ; cout << endl; } } void Fill(data_t buf[], int size) { // Fill abcd ... for(int i = 0; i < size; i++) buf[i] = 'a'+i; // Fill 0123 ... buf += size; for(int i = 0; i < size; i++) buf[i] = '0'+i; } void TestCase_01(void) { int r = 2, c = 10; int size = r*c; data_t *A = new data_t[size]; Fill(A, c); Print2DArray(A, r, c), cout << endl; MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r), cout << endl; delete[] A; } int main() { TestCase_01(); return 0; }
Java import java.util.*; class GFG { static int HASH_SIZE = 128; public static String padLeft(String s, int n) { return String.format("%" + n + "s", s); } static void Print2DArray(char[] A, int nr, int nc) { int size = nr * nc; for (int i = 0; i < size; i++) System.out.print( padLeft(String.valueOf(A[i]), 4)); System.out.print("\n"); } static void MatrixTransposeInplaceArrangement(char[] A, int r, int c) { int size = r * c - 1; char t; // holds element to be replaced, eventually // becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator int b = 1; // hash to mark moved elements b |= (1 << size); i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%size next = (i * r) % size; char temp = t; t = A[next]; A[next] = temp; b |= (1 << i); i = next; } while (i != cycleBegin); // Get Next Move (what about querying random // location?) for (i = 1; i < size && ((b & (1 << i)) != 0); i++) ; System.out.print("\n"); } } static void Fill(char[] buf, int size) { // Fill abcd ... char[] intters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; for (var i = 0; i < size; i++) buf[i] = intters[i]; // Fill 0123 ... for (var i = size; i < 2 * size; i++) buf[i] = (char)(48 + i - size); } static void TestCase_01() { int r = 2, c = 10; int size = r * c; char[] A = new char[size]; Fill(A, c); Print2DArray(A, r, c); MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r); System.out.print("\n"); } public static void main(String[] args) { TestCase_01(); } } // This code is contributed by phasing17.
Python3 HASH_SIZE = 128 def Print2DArray(A, nr, nc): size = nr*nc for i in range(size): print(str(A[i]).rjust(4), end="") def MatrixTransposeInplaceArrangement(A, r, c): size = r*c - 1 b = 1 # hash to mark moved elements b |= (1 << size) i = 1 # Note that A[0] and A[size-1] won't move while(i < size): cycleBegin = i t = A[i] while True: # Input matrix [r x c] # Output matrix [c x r] # i_new = (i*r)%size next1 = (i*r) % size t, A[next1] = A[next1], t b |= (1 << i) i = next1 if (i == cycleBegin): break # Get next1 Move (what about querying random location?) i = 1 while (i < size and (b & (1 << i)) != 0): i += 1 print() def Fill(buf, size): # Fill abcd ... letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] for i in range(size): buf[i] = letters[i] # Fill 0123 .. for i in range(size, 2 * size): buf[i] = str(i - size) def TestCase_01(): r = 2 c = 10 size = r*c A = [0] * size Fill(A, c) Print2DArray(A, r, c) MatrixTransposeInplaceArrangement(A, r, c) Print2DArray(A, c, r) print() TestCase_01()
C# using System; using System.Collections.Generic; class GFG { static int HASH_SIZE = 128; static void Print2DArray(char[] A, int nr, int nc) { int size = nr * nc; for (int i = 0; i < size; i++) Console.Write( Convert.ToString(A[i]).PadLeft(4)); Console.Write("\n"); } static void MatrixTransposeInplaceArrangement(char[] A, int r, int c) { int size = r * c - 1; char t; // holds element to be replaced, eventually // becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator int b = 1; // hash to mark moved elements b |= (1 << size); i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%size next = (i * r) % size; char temp = t; t = A[next]; A[next] = temp; b |= (1 << i); i = next; } while (i != cycleBegin); // Get Next Move (what about querying random // location?) for (i = 1; i < size && ((b & (1 << i)) != 0); i++) ; Console.Write("\n"); } } static void Fill(char[] buf, int size) { // Fill abcd ... char[] intters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; for (var i = 0; i < size; i++) buf[i] = intters[i]; // Fill 0123 ... for (var i = size; i < 2 * size; i++) buf[i] = Convert.ToChar(48 + i - size); } static void TestCase_01() { int r = 2, c = 10; int size = r * c; char[] A = new char[size]; Fill(A, c); Print2DArray(A, r, c); MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r); Console.Write("\n"); } public static void Main(string[] args) { TestCase_01(); } } // This code is contributed by phasing17.
JavaScript let HASH_SIZE = 128 function Print2DArray(A, nr, nc) { let size = nr*nc; for(var i = 0; i < size; i++) process.stdout.write(String(A[i]).padStart(4)) console.log() } function MatrixTransposeInplaceArrangement(A, r, c) { let size = r*c - 1; let t; // holds element to be replaced, eventually becomes next element to move let next; // location of 't' to be moved let cycleBegin; // holds start of cycle let i; // iterator let b = 1; // hash to mark moved elements b |= (1 << size); i = 1; // Note that A[0] and A[size-1] won't move while( i < size ) { cycleBegin = i; t =A[i] do { // Input matrix [r x c] // Output matrix [c x r] // i_new = (i*r)%size next = (i*r)%size; let temp = t t = A[next] A[next] = temp b |= (1 << i); i = next; } while( i != cycleBegin ); // Get Next Move (what about querying random location?) for(i = 1; i < size && (b & (1 << i)); i++) ; console.log() } } function Fill(buf, size) { // Fill abcd ... let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] for(var i = 0; i < size; i++) buf[i] = letters[i]; // Fill 0123 ... for(var i = size; i < 2 * size; i++) buf[i] = String(i - size); } function TestCase_01() { let r = 2, c = 10; let size = r*c; let A = new Array(size); Fill(A, c); Print2DArray(A, r, c); MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r) console.log() } TestCase_01(); // This code is contributed by phasing17.
Output a b c d e f g h i j 0 1 2 3 4 5 6 7 8 9 a 0 b 1 c 2 d 3 e 4 f 5 g 6 h 7 i 8 j 9
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Update 09-July-2016: Notes on space complexity and storage order.
After long time, it happened to review this post. Some readers pointed valid questions on how can it be in-place (?) when we are using bitset as marker (hash in code). Apologies for incorrect perception by looking at the article heading or content. While preparing the initial content, I was thinking of naive implementation using auxiliary space of atleast O(MN) needed to transpose rectangular matrix. The program presented above is using constant space as bitset size is fixed at compile time. However, to support arbitrary size of matrices we need bitset size atleast O(MN) size. One can use a HashMap (amortized O(1) complexity) for marking finished locations, yet HashMap's worst case complexity can be O(N) or O(log N) based on implementation. HashMap space cost also increases based on items inserted. Please note that in-place was used w.r.t. matrix space.
Also, it was assumed that the matrix will be stored in row major ordering (contigueous locations in memory). The reader can derive the formulae, if the matrix is represented in column major order by the programming language (e.g. Fortran/Julia).
Thanks to the readers who pointed these two gaps.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
The post is incomplete without mentioning two links.
1. Aashish covered good theory behind cycle leader algorithm. See his post on string transformation.
2. As usual, Sambasiva demonstrated his exceptional skills in recursion to the problem. Ensure to understand his solution.
Similar Reads
Matrix Data Structure Matrix Data Structure is a two-dimensional array arranged in rows and columns. It is commonly used to represent mathematical matrices and is fundamental in various fields like mathematics, computer graphics, and data processing. Matrices allow for efficient storage and manipulation of data in a stru
2 min read
Matrix or Grid or 2D Array - Complete Tutorial Matrix or Grid is a two-dimensional array mostly used in mathematical and scientific calculations. It is also considered as an array of arrays, where array at each index has the same size. Representation of Matrix Data Structure:As you can see from the below image, the elements are organized in rows
11 min read
Row-wise vs column-wise traversal of matrix Two common ways of traversing a matrix are row-major-order and column-major-order Row Major Order: When matrix is accessed row by row. Column Major Order: When matrix is accessed column by column.Examples: Input : mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output : Row-wise: 1 2 3 4 5 6 7 8 9 Col-wi
6 min read
Applications of Matrices and Determinants Applications of Matrices and Determinants: One application of matrices and determinants is that they can be used to solve linear equations in two or three variables. Matrices and determinants are also used to check the consistency of any system, whether they are consistent or not. This is the most u
6 min read
Basic Operations on Matrix
Traverse a given Matrix using RecursionGiven a matrix mat[][] of size n x m, the task is to traverse this matrix using recursion.Examples: Input: mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Output: 1 2 3 4 5 6 7 8 9Input: mat[][] = [[11, 12, 13], [14, 15, 16], [17, 18, 19]]Output: 11 12 13 14 15 16 17 18 19Approach: Check If the current p
5 min read
Rotate Matrix Clockwise by 1Given a square matrix, the task is to rotate its elements clockwise by one step.Examples:Input 1 2 34 5 6 7 8 9Output: 4 1 27 5 3 8 9 6Input: 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12The idea is to use nested loops to move elements in four directions (right
9 min read
Sort the given matrixGiven a m x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that the matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row âiâ, where 1 <= i <= m-1, the first element is greater than or equal to the last
5 min read
Search element in a sorted matrixGiven a sorted matrix mat[][] of size nxm and an element x, the task is to find if x is present in the matrix or not. Matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row i, where 1 <= i <= n-1, the first element of row i is greater than or equal
13 min read
Program to find transpose of a matrixGiven a matrix of size n X m, find the transpose of the matrix. Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of mat[n][m] is obtained by changing mat[i][j] to mat[j][i].Example:Approach using (N^2) spaceRun a nested loop using two integ
9 min read
Adjoint and Inverse of a MatrixGiven a square matrix, find the adjoint and inverse of the matrix. We strongly recommend you to refer determinant of matrix as a prerequisite for this. Adjoint (or Adjugate) of a matrix is the matrix obtained by taking the transpose of the cofactor matrix of a given square matrix is called its Adjoi
15+ min read
Program to find Determinant of a MatrixThe determinant of a Matrix is defined as a special number that is defined only for square matrices (matrices that have the same number of rows and columns). A determinant is used in many places in calculus and other matrices related to algebra, it actually represents the matrix in terms of a real n
15+ min read
Easy problems on Matrix
Print matrix in zig-zag fashionGiven a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. Example: Input: {{1, 2, 3}{4, 5, 6}{7, 8, 9}}Output: 1 2 4 7 5 3 6 8 9Input : [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]Output:: 1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16Thi
10 min read
Program for scalar multiplication of a matrixGiven a 2D matrix mat[][] with n rows and m columns and a scalar element k, the task is to find out the scalar product of the given matrix.Examples: Input: mat[][] = [[2, 3], [5, 4]]k = 5Output: [[10, 15], [25, 20]]Input:mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]k = 4Output: [[4, 8, 12], [16, 20, 2
4 min read
Print a given matrix in spiral formGiven a matrix mat[][] of size m x n, the task is to print all elements of the matrix in spiral form.Examples: Input: mat[][] = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]Output: [ 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 ]Example of matrix in spiral formInput: mat[]
14 min read
Find distinct elements common to all rows of a matrixGiven a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order. Examples: Input : mat[][] = { {2, 1, 4, 3}, {1, 2, 3, 2}, {3, 6, 2, 3}, {5, 2, 5, 3} } Output : 2 3 Input : mat[][] = { {12, 1, 14, 3, 16}, {14, 2, 1, 3,
15+ min read
Find unique elements in a matrixGiven a matrix mat[][] having n rows and m columns. The task is to find unique elements in the matrix i.e., those elements which are not repeated in the matrix or those elements whose frequency is 1. Examples: Input: mat[][] = [[2, 1, 4, 3], [1, 2, 3, 2], [3, 6, 2, 3], [5, 2, 5, 3]]Output: 4 6Input:
5 min read
Find maximum element of each row in a matrixGiven a matrix mat[][], the task is to find the maximum element of each row.Examples: Input: mat[][] = [[1, 2, 3] [1, 4, 9] [76, 34, 21]]Output :3976Input: mat[][] = [[1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2]]Output :216556The idea is to run the loop for no_of_rows. Check each element inside the r
4 min read
Shift matrix elements row-wise by kGiven a square matrix mat[][] and a number k. The task is to shift the first k elements of each row to the right of the matrix. Examples : Input : mat[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} k = 2 Output :mat[N][N] = {{3, 1, 2} {6, 4, 5} {9, 7, 8}} Input : mat[N][N] = {{1, 2, 3, 4} {5, 6, 7, 8} {9
6 min read
Swap major and minor diagonals of a square matrixGiven a square matrix mat[][] of order n*n, the task is to swap the elements of major and minor diagonals.The major and minor diagonal matrix explanation is given below:Major Diagonal Elements of a Matrix: The Major Diagonal Elements are the ones that occur from the Top Left of the Matrix Down To th
6 min read
Squares of Matrix Diagonal ElementsGiven an integer matrix mat[][] of odd dimensions, the task is to find the square of the elements of the Primary and Secondary diagonals.The Primary and Secondary diagonal matrix explanation is given below:Primary Diagonal Elements of a Matrix: The Primary Diagonal Elements are the ones that occur f
11 min read
Sum of middle row and column in MatrixGiven an integer matrix of odd dimensions (3 * 3, 5 * 5). then the task is to find the sum of the middle row & column elements. Examples: Input : 2 5 7 3 7 2 5 6 9 Output : Sum of middle row = 12 Sum of middle column = 18 Input : 1 3 5 6 7 3 5 3 2 1 1 2 3 4 5 7 9 2 1 6 9 1 5 3 2 Output : Sum of
7 min read
Program to check idempotent matrixGiven a square matrix mat[][] of order n*n, the task is to check if it is an Idempotent Matrix or not.Idempotent matrix: A matrix is said to be an idempotent matrix if the matrix multiplied by itself returns the same matrix, i.e. the matrix mat[][] is said to be an idempotent matrix if and only if M
5 min read
Program to check diagonal matrix and scalar matrixGiven a square matrix mat[][] of order n*n, the task is to check if it is a Diagonal Matrix and Scalar matrix.Diagonal Matrix: A square matrix is said to be a diagonal matrix if the elements of the matrix except the main diagonal are zero. A square null matrix is also a diagonal matrix whose main di
9 min read
Program to check Identity MatrixGiven a square matrix mat[][] of order n*n, the task is to check if it is an Identity Matrix.Identity Matrix: A square matrix is said to be an identity matrix if the elements of main diagonal are one and all other elements are zero. The identity Matrix is also known as the Unit Matrix. Examples: Inp
5 min read
Mirror of matrix across diagonalGiven a 2-D array of order N x N, print a matrix that is the mirror of the given tree across the diagonal. We need to print the result in a way: swap the values of the triangle above the diagonal with the values of the triangle below it like a mirror image swap. Print the 2-D array obtained in a mat
14 min read
Program for addition of two matricesGiven two N x M matrices. Find a N x M matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices. Approach: Below is the idea to solve the problem.Iterate over every cell of matrix (i, j), add the corresponding values of the two matrices
5 min read
Program for subtraction of matricesGiven two m x n matrices m1 and m2, the task is to subtract m2 from m1 and return res.Input: m1 = {{1, 2}, {3, 4}}, m2 = {{4, 3}, {2, 1}}Output: {{-3, -1}, {1, 3}}Input: m1 = {{3, 3, 3}, {3, 3, 3}}, m1 = {{2, 2, 2}, {1, 1, 1}},Output: {{1, 1, 1}, {2, 2, 2}},We traverse both matrices element by eleme
5 min read
Intermediate problems on Matrix
Program for Conway's Game Of Life | Set 1Given a Binary Matrix mat[][] of order m*n. A cell with a value of zero is a Dead Cell, while a cell with a value of one is a Live Cell. The state of cells in a matrix mat[][] is known as Generation. The task is to find the next generation of cells based on the following rules:Any live cell with few
12 min read
Program to multiply two matricesGiven two matrices, the task is to multiply them. Matrices can either be square or rectangular:Examples: (Square Matrix Multiplication)Input: m1[m][n] = { {1, 1}, {2, 2} }m2[n][p] = { {1, 1}, {2, 2} }Output: res[m][p] = { {3, 3}, {6, 6} }(Rectangular Matrix Multiplication)Input: m1[3][2] = { {1, 1},
7 min read
Rotate an Image 90 Degree CounterclockwiseGiven an image represented by m x n matrix, rotate the image by 90 degrees in counterclockwise direction. Please note the dimensions of the result matrix are going to n x m for an m x n input matrix.Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13Input: 1
6 min read
Check if all rows of a matrix are circular rotations of each otherGiven a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1 Output: Yes All rows are rotated permutation of each other. Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2 Output: No Explanation : As 3, 2, 1
8 min read
Largest Cross Bordered SquareGiven a matrix mat[][] of size n x n where every element is either 'O' or 'X', the task is to find the size of the largest square subgrid that is completely surrounded by 'X', i.e. the largest square where all its border cells are 'X'. Examples: Input: mat[][] = [ ['X', 'X'], ['X', 'X'] ]Output: 2Ex
15 min read
Count zeros in a row wise and column wise sorted matrixGiven a n x n binary matrix (elements in matrix can be either 1 or 0) where each row and column of the matrix is sorted in ascending order, count number of 0s present in it.Examples: Input: [0, 0, 0, 0, 1][0, 0, 0, 1, 1][0, 1, 1, 1, 1][1, 1, 1, 1, 1][1, 1, 1, 1, 1]Output: 8Input: [0, 0][0, 0]Output:
6 min read
Queries in a MatrixGiven two integers m and n, that describes the order m*n of a matrix mat[][], initially filled with integers from 1 to m*n sequentially in a row-major order. Also, there is a 2d array query[][] consisting of q queries, which contains three integers each, where the first integer t describes the type
15 min read
Find pairs with given sum such that elements of pair are in different rowsGiven a matrix of distinct values and a sum. The task is to find all the pairs in a given matrix whose summation is equal to the given sum. Each element of a pair must be from different rows i.e; the pair must not lie in the same row.Examples: Input : mat[][] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 1
15+ min read
Find all permuted rows of a given row in a matrixGiven a matrix mat[][] of order m*n, and an index ind. The task is to find all the rows in the matrix mat[][] which are permutations of rows at index ind.Note: All the elements of a row are distinct.Examples: Input: mat[][] = [[3, 1, 4, 2], [1, 6, 9, 3], [1, 2, 3, 4], [4, 3, 2, 1]] ind = 3 Output: 0
9 min read
Find number of transformation to make two Matrix EqualGiven two matrices a and b of size n*m. The task is to find the required number of transformation steps so that both matrices become equal. Print -1 if this is not possible. The transformation step is as follows: Select any one matrix out of two matrices. Choose either row/column of the selected mat
8 min read
Inplace (Fixed space) M x N size matrix transposeGiven an M x N matrix, transpose the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array. If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D array across it's diagonal (try yourself). How to transpose an arbitrary size matr
15+ min read
Minimum flip required to make Binary Matrix symmetricGiven a Binary Matrix mat[][] of size n x n, consisting of 1s and 0s. The task is to find the minimum flips required to make the matrix symmetric along the main diagonal.Examples : Input: mat[][] = [[0, 0, 1], [1, 1, 1], [1, 0, 0]];Output: 2Value of mat[1][0] is not equal to mat[0][1].Value of mat[2
8 min read
Magic Square of Odd OrderGiven a positive integer n, your task is to generate a magic square of order n * n. A magic square of order n is an nâ¯*â¯n grid filled with the numbers 1 through n² so that every row, every column, and both main diagonals each add up to the same total, called the magic constant (or magic sum) M. Beca
15+ min read
Hard problems on Matrix
Number of IslandsGiven an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in
15+ min read
A Boolean Matrix QuestionGiven a boolean matrix mat where each cell contains either 0 or 1, the task is to modify it such that if a matrix cell matrix[i][j] is 1 then all the cells in its ith row and jth column will become 1.Examples:Input: [[1, 0], [0, 0]]Output: [[1, 1], [1, 0]]Input: [[1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0
15+ min read
Matrix Chain MultiplicationGiven the dimension of a sequence of matrices in an array arr[], where the dimension of the ith matrix is (arr[i-1] * arr[i]), the task is to find the most efficient way to multiply these matrices together such that the total number of element multiplications is minimum. When two matrices of size m*
15+ min read
Maximum size rectangle binary sub-matrix with all 1sGiven a 2d binary matrix mat[][], the task is to find the maximum size rectangle binary-sub-matrix with all 1's. Examples: Input: mat = [ [0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 0, 0] ]Output : 8Explanation : The largest rectangle with only 1's is from (1, 0) to (2, 3) which is[1, 1, 1, 1][
15 min read
Construct Ancestor Matrix from a Given Binary TreeGiven a Binary Tree where all values are from 0 to n-1. Construct an ancestor matrix mat[n][n] where the ancestor matrix is defined as below. mat[i][j] = 1 if i is ancestor of jmat[i][j] = 0, otherwiseExamples: Input: Output: {{0 1 1} {0 0 0} {0 0 0}}Input: Output: {{0 0 0 0 0 0} {1 0 0 0 1 0} {0 0
15+ min read
K'th element in spiral form of matrixGiven a matrix of size n * m. You have to find the kth element which will obtain while traversing the matrix spirally starting from the top-left corner of the matrix.Examples:Input: mat[][] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], k = 4Output: 6Explanation: Spiral traversal of matrix: {1, 2, 3, 6, 9,
13 min read
Largest Plus or '+' formed by all ones in a binary square matrixGiven an n à n binary matrix mat consisting of 0s and 1s. Your task is to find the size of the largest â+â shape that can be formed using only 1s. A â+â shape consists of a center cell with four arms extending in all four directions (up, down, left, and right) while remaining within the matrix bound
10 min read
Shortest path in a Binary MazeGiven an M x N matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.Note: You can move into an adjacent cell in one of the four directions, Up, Down, Left, and
15+ min read
Maximum sum square sub-matrix of given sizeGiven a 2d array mat[][] of order n * n, and an integer k. Your task is to find a submatrix of order k * k, such that sum of all the elements in the submatrix is maximum possible.Note: Matrix mat[][] contains zero, positive and negative integers.Examples:Input: k = 3mat[][] = [ [ 1, 2, -1, 4 ] [ -8,
15+ min read
Validity of a given Tic-Tac-Toe board configurationA Tic-Tac-Toe board is given after some moves are played. Find out if the given board is valid, i.e., is it possible to reach this board position after some moves or not.Note that every arbitrary filled grid of 9 spaces isn't valid e.g. a grid filled with 3 X and 6 O isn't valid situation because ea
15+ min read
Minimum Initial Points to Reach DestinationGiven a m*n grid with each cell consisting of positive, negative, or no points i.e., zero points. From a cell (i, j) we can move to (i+1, j) or (i, j+1) and we can move to a cell only if we have positive points ( > 0 ) when we move to that cell. Whenever we pass through a cell, points in that cel
15+ min read
Program for Sudoku GeneratorGiven an integer k, the task is to generate a 9 x 9 Sudoku grid having k empty cells while following the below set of rules:In all 9 submatrices 3x3, the elements should be 1-9, without repetition.In all rows, there should be elements between 1-9, without repetition.In all columns, there should be e
15+ min read