medium
0 views

Decreasing String in Center – Pattern

Print a pattern where a string is displayed with characters removed from the center in each subsequent line, replaced by asterisks.

Understand the Problem

Problem Statement

A string S is passed as the input to the program. The program must print the pattern as shown in the Example Input/Output sections.

Note: The length of the string is always even.

Constraints

  • 1 <= Length of the string <= 100
  • String contains only lowercase letters
  • String length is always even

Examples

Example 1
Input
barber
Output
barber
*baer*
**br**
******
Explanation

Starting with 'barber', we remove 1 character from each side of the center in each step: 'barber' → '*baer*' (removed 'r' and 'b') → '**br**' (removed 'a' and 'e') → '******' (removed 'b' and 'r').

Example 2
Input
database
Output
database
*datase*
**dase**
***de***
********
Explanation

Starting with 'database', we remove characters from the center progressively: 'database' → '*datase*' (removed 't' and 'a') → '**dase**' (removed 'a' and 's') → '***de***' (removed 'd' and 'a') → '********' (removed 'a' and 't').

Solution

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

void printAsterisks(int count) {
    for (int i = 0; i < count; i++) {
        printf("*");
    }
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);
    int len = strlen(str);
    if (str[len-1] == '\n') {
        str[len-1] = '\0';
        len--;
    }
    
    int half = len / 2;
    
    for (int i = 0; i <= half; i++) {
        // Print leading asterisks
        printAsterisks(i);
        
        // Print left portion (first half-i characters)
        for (int j = 0; j < half - i; j++) {
            printf("%c", str[j]);
        }
        
        // Print right portion (last half-i characters)
        for (int j = len - (half - i); j < len; j++) {
            printf("%c", str[j]);
        }
        
        // Print trailing asterisks
        printAsterisks(i);
        
        printf("\n");
    }
    
    return 0;
}
Time:O(n²) where n is the length of the string
Space:O(1) - only using a constant amount of extra space
Approach:

The C solution uses a function printAsterisks to handle asterisk printing. The main logic:

  1. Read the input string and calculate its length
  2. For each iteration i from 0 to half the string length:
  3. Print i leading asterisks
  4. Print the first (half-i) characters from the left side
  5. Print the last (half-i) characters from the right side
  6. Print i trailing asterisks
  7. Move to next line

Visual Explanation

Loading diagram...