Open In App

Construct a square Matrix using digits of given number N based on given pattern

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
3 Likes
Like
Report

Given an integer N, The task is to construct a matrix mat[][] of size M x M ('M' is the number of digits in the given integer) such that each diagonal of the matrix contains the same digit, placed according to the position of the digits in the given integer and then again repeat the steps from the back.

Examples:

Input: N = 123
Output: {{1, 2, 3}, 
               {2, 3, 2}, 
               {3, 2, 1}}
Explanation: The desired matrix must be of size 3*3. The digits of N are 1, 2, and 3. Placing 1, 2 and 3 along the diagonals from the top left cell till the Nth diagonal, and 2, 1 just after the Nth diagonal till the bottom-most cell.

Input: N = 3219
Output: {{3, 2, 1, 9}, {2, 1, 9, 1}, {1, 9, 1, 2}, {9, 1, 2, 3}}

 

Approach: The task can be solved by traversing the matrix in a diagonal fashion and assigning the cell values according to the corresponding digit in the given number.

  1. Extract and store the digits of the given integer in a vector say v.
  2. Again store the digits in reverse order for 2nd half diagonal of the matrix.
  3. Assign the digits in the desired order.
  4. Print the matrix.

Below is the implementation of the above approach: 

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to construct the matrix
void constructMatrix(int n)
{
    // Vector to store the
    // digits of the integer
    vector<int> v;

    // Extracting the digits
    // from the integer
    while (n > 0) {
        v.push_back(n % 10);
        n = n / 10;
    }

    // Reverse the vector
    reverse(v.begin(), v.end());

    // Size of the vector
    int N = v.size();

    // Loop to store the digits in
    // reverse order in the same vector
    for (int i = N - 2; i >= 0; i--) {
        v.push_back(v[i]);
    }

    // Matrix to be constructed
    int mat[N][N];

    // Assign the digits and
    // print the desired matrix
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            mat[i][j] = v[i + j];
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
}

// Driver Code
int main()
{
    int n = 3219;

    // Passing n to constructMatrix function
    constructMatrix(n);

    return 0;
}
Java Python3 C# JavaScript

 
 


Output: 
3 2 1 9 
2 1 9 1 
1 9 1 2 
9 1 2 3

 


 

Time Complexity: O(N2)
Auxiliary Space: O(1)


 


Practice Tags :

Similar Reads