medium
0 views

String X-Pattern

Print a string in an X pattern using the characters from the string on the diagonals and asterisks elsewhere

Understand the Problem

Problem Statement

The program must accept a string S as the input. The program must print the desired pattern as shown in the Example Input/Output section.

Constraints

  • 3 ≤ Length of S ≤ 50
  • String S consists of uppercase and lowercase letters
  • The pattern is a square matrix of size N×N where N is the length of the string
  • Characters from the string are placed on the main diagonal and anti-diagonal
  • All other positions are filled with asterisks (*)

Examples

Example 1
Input
water
Output
w * * * a
* t * e *
* * r * *
* t * e *
w * * * a
Explanation

For the string 'water' (length 5), we create a 5×5 matrix. The characters 'w', 'a', 't', 'e', 'r' are placed on the main diagonal (positions 0,0; 1,1; 2,2; 3,3; 4,4) and the anti-diagonal (positions 0,4; 1,3; 2,2; 3,1; 4,0). Note that position (2,2) is shared by both diagonals, so 'r' appears there. All other positions contain asterisks.

Example 2
Input
OFFICE
Output
O * * * * F
* F * * I *
* * C E * *
* * C E * *
* F * * I *
O * * * * F
Explanation

For the string 'OFFICE' (length 6), we create a 6×6 matrix. The characters 'O', 'F', 'F', 'I', 'C', 'E' are placed on both diagonals. The main diagonal has positions (0,0), (1,1), (2,2), (3,3), (4,4), (5,5) and the anti-diagonal has positions (0,5), (1,4), (2,3), (3,2), (4,1), (5,0). All other positions contain asterisks.

Solution

#include <stdio.h>
#include <string.h>

int main() {
    char s[51];
    fgets(s, sizeof(s), stdin);
    
    // Remove newline if present
    int len = strlen(s);
    if (s[len-1] == '\n') {
        s[len-1] = '\0';
        len--;
    }
    
    // Create and print the X pattern
    for (int i = 0; i < len; i++) {
        for (int j = 0; j < len; j++) {
            if (i == j || j == len - i - 1) {
                printf("%c ", s[i]);
            } else {
                printf("* ");
            }
        }
        printf("\n");
    }
    
    return 0;
}
Time:O(N²) where N is the length of the string
Space:O(1) - only using the input string and a few variables
Approach:

C Solution Explanation:

  1. Input Reading: Use fgets() to read the string and manually remove the newline character
  2. Pattern Generation: Use nested loops to iterate through each position in the N×N matrix
  3. Diagonal Logic: Check if current position (i,j) is on main diagonal (i == j) or anti-diagonal (j == len-i-1)
  4. Output: Print the character from the string at diagonal positions, asterisk elsewhere, with spaces between characters
  5. Row Separation: Print newline after each row

This approach directly maps the mathematical definition of the X pattern to code.

Visual Explanation

Loading diagram...