medium
0 views

Inverted L-Shaped Matrix

Print the elements of a square matrix in an inverted L-shape pattern row by row

Understand the Problem

Problem Statement

Given a square matrix of size S, print the matrix in the format given in Example Input/Output section.

Input Format:
The first line contains the value size S of the matrix.
The next S lines contain S values of a given row separated by a space.

Output Format:
The S lines denote the inverted L-shaped matrix.

Boundary Condition:
1 <= S <= 100

Constraints

  • Matrix size S must be between 1 and 100 (inclusive)
  • Matrix elements can be any integer values
  • Input must be a square matrix (S x S)
  • Time complexity should be O(S²) for reading input and O(S²) for output generation
  • Space complexity is O(S²) for storing the matrix

Examples

Example 1
Input
3
11 12 13
21 22 23
31 32 33
Output
11
21 22 12
31 32 33 23 13
Explanation

For a 3x3 matrix: - Line 1: First element of row 1 (11) - Line 2: First 2 elements of row 2 (21, 22) + element at column 1 of row 1 (12) - Line 3: First 3 elements of row 3 (31, 32, 33) + elements at column 2 of rows 2 and 1 (23, 13)

Example 2
Input
6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
Output
1
1 2 2
1 2 3 3 3
1 2 3 4 4 4 4
1 2 3 4 5 5 5 5 5
1 2 3 4 5 6 6 6 6 6 6
Explanation

For a 6x6 matrix where all rows are identical: - Each line follows the inverted L pattern - Line 4: First 4 elements of row 4 (1,2,3,4) + element at column 3 from rows 3,2,1 (4,4,4,4) - The pattern continues similarly for all lines

Solution

#include <stdio.h>

int main() {
    int s;
    scanf("%d", &s);
    
    int matrix[100][100];
    
    // Read the matrix
    for (int i = 0; i < s; i++) {
        for (int j = 0; j < s; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Print inverted L-shape pattern
    for (int i = 0; i < s; i++) {
        // Print first (i+1) elements of current row
        for (int j = 0; j <= i; j++) {
            printf("%d ", matrix[i][j]);
        }
        
        // Print elements at column i from previous rows
        for (int k = i - 1; k >= 0; k--) {
            printf("%d ", matrix[k][i]);
        }
        
        printf("\n");
    }
    
    return 0;
}
Time:O(S²) - We read S² elements and print up to S² elements in the worst case
Space:O(S²) - We store the S×S matrix in memory
Approach:

The C solution follows the algorithm described in the approach:

  1. Reads the matrix size S and validates it's within bounds
  2. Allocates a 100x100 array (sufficient for max constraint S ≤ 100)
  3. Reads S rows of S integers each using nested loops
  4. For each row i, prints:
    • First (i+1) elements from current row (matrix[i][0] to matrix[i][i])
    • Elements at column i from all previous rows (matrix[i-1][i] down to matrix[0][i])
  5. Uses printf with space separation and newlines for proper formatting

Visual Explanation

Loading diagram...