medium
0 views

Digital 7-Shaped String

Print a given string in a 7-shaped digital format where characters form a descending diagonal pattern

Understand the Problem

Problem Statement

Given an input string S, print the string in a 'Digital 7-Shaped' format. The output should form a pattern where characters create a descending diagonal that resembles the shape of a digital 7.

The first character appears in the first row repeated across all columns, then subsequent rows show the pattern where characters from the original string fill positions from left to right until a diagonal boundary, then characters from the original string fill from right to left.

Constraints

  • 1 < Length of S < 1000
  • S may contain alphabets, numbers, and special characters
  • Each character in the output should be separated by a space

Examples

Example 1
Input
xyz
Output
x x x
y y x
z y x
Explanation
For input 'xyz' (length 3):
Row 0: Print 'x' for first (3-0)=3 positions: x x x
Row 1: Print 'y' for first (3-1)=2 positions, then 'x' (from position 0): y y x
Row 2: Print 'z' for first (3-2)=1 position, then 'y', 'x': z y x
Example 2
Input
123456
Output
1 1 1 1 1 1
2 2 2 2 2 1
3 3 3 3 2 1
4 4 4 3 2 1
5 5 4 3 2 1
6 5 4 3 2 1
Explanation
For input '123456' (length 6):
Row 0: Print '1' for first 6 positions: 1 1 1 1 1 1
Row 1: Print '2' for first 5 positions, then '1': 2 2 2 2 2 1
Row 2: Print '3' for first 4 positions, then '2', '1': 3 3 3 3 2 1
And so on, creating the descending diagonal pattern.

Solution

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

int main() {
    char a[1000];
    fgets(a, sizeof(a), stdin);
    
    // Remove newline character if present
    int l = strlen(a);
    if (a[l-1] == '\n') {
        a[l-1] = '\0';
        l--;
    }
    
    for (int i = 0; i < l; i++) {
        int k = i;
        for (int j = 0; j < l; j++) {
            if (j < (l - i)) {
                printf("%c ", a[i]);
            } else {
                printf("%c ", a[k - 1]);
                k--;
            }
        }
        printf("\n");
    }
    
    return 0;
}
Time:O(n²) where n is the length of the string - we have nested loops each going up to n
Space:O(n) for storing the input string
Approach:

Step-by-step explanation:

  1. Input Reading: Read the string using fgets() and handle the newline character that gets included
  2. Length Calculation: Get the string length, adjusting if newline was present
  3. Outer Loop (i): Iterates through each row from 0 to length-1
  4. Inner Loop (j): For each position in the current row:
    • If j < (l-i): Print the i-th character (creates the left portion)
    • Otherwise: Print characters in reverse order starting from position i-1
  5. Output: Each character is followed by a space, and each row ends with a newline

Visual Explanation

Loading diagram...