Make a perfect Pyramid by printing letters of a given String
Last Updated :
16 Oct, 2023
Given a string str, the task is to print a perfect pyramid by printing the characters of the given string.
Examples:
Input: str = “GEEKSFORGEEKS”
Output:
G
E E K
S F O R G
not including E K S because they make our pyramid imperfect. i.e.
G
E E K
S F O R G
E K S
Input: str = “PyramidOfStrings”
Output:
P
y r a
m i d O f
S t r i n g s
Approach: To solve the problem follow the above idea:
- Find the rows up to which a perfect pyramid can be made.
- After finding the rows and number of elements used in the string, implements the nested loop till that row.
- Take a pointer that traverses the string and prints the following character.
Below are the steps for the above approach:
- Initialize a variable say n to store the length of the string.
- Initialize two variables x and ele, where x will store the number of elements in a particular row and ele will store the number of total elements used from string till that row up to that row.
- Initialize variable rows up to which the outer loop will run.
- There are 2 inner loops one for printing the starting spaces of every row and another row for printing the character.
- Take a pointer ch that traverses the string and prints the following character.
- In every nth row there are 2*row-1 elements So print the character in a row until k != 2*row-1.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void perfectPyramid(string str)
{
int n = str.length();
int x = 1;
int ele = 1;
int rows = 0;
while (ele <= n) {
x += 2;
ele += x;
rows++;
}
int ch = 0;
for ( int i = 1, k = 0; i <= rows; ++i, k = 0) {
for ( int space = 1; space <= rows - i; ++space) {
cout << " " ;
}
while (k != 2 * i - 1) {
cout << str[ch] << " " ;
++k;
ch++;
}
cout << endl;
}
}
int main()
{
string str = "PyramidOfStrings" ;
perfectPyramid(str);
return 0;
}
|
Java
import java.util.*;
public class PerfectPyramid {
public static void perfectPyramid(String str)
{
int n = str.length();
int x = 1 ;
int ele = 1 ;
int rows = 0 ;
while (ele <= n) {
x += 2 ;
ele += x;
rows++;
}
int ch = 0 ;
for ( int i = 1 , k = 0 ; i <= rows; ++i, k = 0 ) {
for ( int space = 1 ; space <= rows - i;
++space) {
System.out.print( " " );
}
while (k != 2 * i - 1 ) {
System.out.print(str.charAt(ch) + " " );
++k;
ch++;
}
System.out.println();
}
}
public static void main(String[] args)
{
String str = "PyramidOfStrings" ;
perfectPyramid(str);
}
}
|
Python3
def perfectPyramid( str ):
n = len ( str )
x = 1
ele = 1
rows = 0
while ele < = n:
x + = 2
ele + = x
rows + = 1
ch = 0
for i in range ( 1 , rows + 1 ):
for space in range ( 1 , rows - i + 1 ):
print ( " " , end = "")
k = 0
while k ! = 2 * i - 1 :
print ( str [ch], end = " " )
k + = 1
ch + = 1
if ch = = n:
break
print ()
if __name__ = = "__main__" :
str = "PyramidOfStrings"
perfectPyramid( str )
|
C#
using System;
public class Program {
static void perfectPyramid( string str)
{
int n = str.Length;
int x = 1;
int ele = 1;
int rows = 0;
while (ele <= n) {
x += 2;
ele += x;
rows++;
}
int ch = 0;
for ( int i = 1, k = 0; i <= rows; ++i, k = 0) {
for ( int space = 1; space <= rows - i;
++space) {
Console.Write( " " );
}
while (k != 2 * i - 1) {
Console.Write(str[ch] + " " );
++k;
ch++;
}
Console.WriteLine();
}
}
static void Main()
{
string str = "PyramidOfStrings" ;
perfectPyramid(str);
}
}
|
Javascript
function perfectPyramid(str) {
let n = str.length;
let x = 1;
let ele = 1;
let rows = 0;
while (ele <= n) {
x += 2;
ele += x;
rows++;
}
let ch = 0;
for (let i = 1, k = 0; i <= rows; ++i, k = 0) {
for (let space = 1; space <= rows - i; ++space) {
process.stdout.write( " " );
}
while (k != 2 * i - 1) {
process.stdout.write(str[ch] + " " );
++k;
ch++;
}
process.stdout.write( "\n" );
}
}
let str = "PyramidOfStrings" ;
perfectPyramid(str);
|
Output
P
y r a
m i d O f
S t r i n g s
Time Complexity: O (rows*x), where rows are the total number of rows and x is the total number of elements in a particular row.
Auxiliary Space: O(1)
Another approach:
We can solve the problem using string slicing and repetition.
Steps:
Below are the steps for the above approach:
- First, take the string.
- Then, iterate over the length of the string using a for loop to calculate total spaces.
- Again iterate and in each iteration of the loop:
- Check if it is possible to print the remaining string in perfect pyramid shape.
- If not possible break the loop.
- If possible:
- Calculate and print required spaces
- Slice the input string up to the index (i+1)2 form i2 index using the string[(i*i):(i+1)*(i+1)] syntax.
- Print the repeated substring in a new line using the print() function.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
using namespace std;
void printTriangle(string str)
{
int k = 0;
for ( int i = 0; i < str.length(); i++) {
if (str.length() >= (i + 1) * (i + 1)) {
k += 1;
}
}
k -= 1;
for ( int i = 0; i < str.length(); i++) {
string spaces = " " ;
if (str.length() < (i + 1) * (i + 1)) {
break ;
}
spaces = string(k, ' ' );
cout << spaces;
k -= 1;
cout << str.substr(i * i, (i + 1) * (i + 1) - i * i)
<< endl;
}
}
int main()
{
string str = "PyramidOfStrings" ;
printTriangle(str);
return 0;
}
|
Java
public class Main {
static void printTriangle(String str)
{
int k = 0 ;
for ( int i = 0 ; i * i < str.length(); i++) {
k += 1 ;
}
k -= 1 ;
for ( int i = 0 ; i < str.length(); i++) {
String spaces = " " ;
if (i * i >= str.length()) {
break ;
}
spaces = " " .repeat(k);
int start = i * i;
int end
= Math.min((i + 1 ) * (i + 1 ), str.length());
System.out.print(spaces);
k -= 1 ;
System.out.println(str.substring(start, end));
}
}
public static void main(String[] args)
{
String str = "PyramidOfStrings" ;
printTriangle(str);
}
}
|
Python3
def printTriangle( str ):
k = 0
for i in range ( len ( str )):
if ( len ( str ) > = (i + 1 ) * (i + 1 )):
k + = 1
k - = 1
for i in range ( len ( str )):
s = " "
if ( len ( str ) < (i + 1 ) * (i + 1 )):
break
s = s * k
print (s,end = '')
k - = 1
print ( str [(i * i):(i + 1 ) * (i + 1 )])
if __name__ = = '__main__' :
str = "PyramidOfStrings"
printTriangle( str )
|
C#
using System;
public class Program
{
public static void PrintTriangle( string str)
{
int k = 0;
for ( int i = 0; i < str.Length; i++)
{
if (str.Length >= (i + 1) * (i + 1))
{
k += 1;
}
}
k -= 1;
for ( int i = 0; i < str.Length; i++)
{
string s = " " ;
if (str.Length < (i + 1) * (i + 1))
{
break ;
}
s = new string ( ' ' , k);
Console.Write(s);
k -= 1;
Console.WriteLine(str.Substring(i * i, (i + 1) * (i + 1) - i * i));
}
}
public static void Main( string [] args)
{
string str = "PyramidOfStrings" ;
PrintTriangle(str);
}
}
|
Javascript
function printTriangle(str) {
let k = 0;
for (let i = 0; i < str.length; i++) {
if (str.length >= (i + 1) * (i + 1)) {
k += 1;
}
}
k -= 1;
for (let i = 0; i < str.length; i++) {
let s = " " ;
if (str.length < (i + 1) * (i + 1)) {
break ;
}
s = s.repeat(k);
console.log(s, end= '' );
k -= 1;
console.log(str.slice(i * i, (i + 1) * (i + 1)));
}
}
let str = "PyramidOfStrings" ;
printTriangle(str);
|
Output
P
yra
midOf
Strings
Time Complexity: O (rows*x), where rows are the total number of rows and x is the total number of elements in a particular row.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...