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 Gnot including E K S because they make our pyramid imperfect. i.e.
G
E E K
S F O R G
E K SInput: 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++
// C++ code to make a perfect // pyramid from a given string. #include <iostream> using namespace std; // Funtion that prints perfect pyramid void perfectPyramid(string str) { // To store length of string int n = str.length(); // To store total elements in // a perticular row int x = 1; // To store total number elements // used upto that row int ele = 1; // To store total number of rows int rows = 0; // Loop to determine the rows and // elements upto which string is used while (ele <= n) { x += 2; ele += x; rows++; } // To travese the given string int ch = 0; // Nested loop to make the perfect // pyramid from given string for ( int i = 1, k = 0; i <= rows; ++i, k = 0) { // Loop to print initial // spaces of every row for ( int space = 1; space <= rows - i; ++space) { cout << " " ; } // Loop to print character // of the string while (k != 2 * i - 1) { cout << str[ch] << " " ; ++k; ch++; } cout << endl; } } // Drivers code int main() { string str = "PyramidOfStrings" ; // Function call perfectPyramid(str); return 0; } |
Java
// Java code to make a perfect // pyramid from a given string. import java.util.*; public class PerfectPyramid { // Function that prints perfect pyramid public static void perfectPyramid(String str) { // To store length of string int n = str.length(); // To store total elements in // a perticular row int x = 1 ; // To store total number elements // used upto that row int ele = 1 ; // To store total number of rows int rows = 0 ; // Loop to determine the rows and // elements upto which string is used while (ele <= n) { x += 2 ; ele += x; rows++; } // To traverse the given string int ch = 0 ; // Nested loop to make the perfect // pyramid from given string for ( int i = 1 , k = 0 ; i <= rows; ++i, k = 0 ) { // Loop to print initial // spaces of every row for ( int space = 1 ; space <= rows - i; ++space) { System.out.print( " " ); } // Loop to print character // of the string while (k != 2 * i - 1 ) { System.out.print(str.charAt(ch) + " " ); ++k; ch++; } System.out.println(); } } // Driver code public static void main(String[] args) { String str = "PyramidOfStrings" ; // Function call perfectPyramid(str); } } // This code is contributed by Prajwal Kandekar |
Python3
# Python code to make a perfect # pyramid from a given string. # Function that prints perfect pyramid def perfectPyramid( str ): # To store length of string n = len ( str ) # To store total elements in # a perticular row x = 1 # To store total number elements # used upto that row ele = 1 # To store total number of rows rows = 0 # Loop to determine the rows and # elements upto which string is used while ele < = n: x + = 2 ele + = x rows + = 1 # To traverse the given string ch = 0 # Nested loop to make the perfect # pyramid from given string for i in range ( 1 , rows + 1 ): # Loop to print initial # spaces of every row for space in range ( 1 , rows - i + 1 ): print ( " " , end = "") # Loop to print character # of the string k = 0 while k ! = 2 * i - 1 : print ( str [ch], end = " " ) k + = 1 ch + = 1 if ch = = n: break print () # Drivers code if __name__ = = "__main__" : str = "PyramidOfStrings" # Function call perfectPyramid( str ) |
C#
// C# code to make a perfect // pyramid from a given string. using System; public class Program { // Function that prints perfect pyramid static void perfectPyramid( string str) { // To store length of string int n = str.Length; // To store total elements in // a perticular row int x = 1; // To store total number elements // used upto that row int ele = 1; // To store total number of rows int rows = 0; // Loop to determine the rows and // elements upto which string is used while (ele <= n) { x += 2; ele += x; rows++; } // To travese the given string int ch = 0; // Nested loop to make the perfect // pyramid from given string for ( int i = 1, k = 0; i <= rows; ++i, k = 0) { // Loop to print initial // spaces of every row for ( int space = 1; space <= rows - i; ++space) { Console.Write( " " ); } // Loop to print character // of the string while (k != 2 * i - 1) { Console.Write(str[ch] + " " ); ++k; ch++; } Console.WriteLine(); } } // Drivers code static void Main() { string str = "PyramidOfStrings" ; // Function call perfectPyramid(str); } } |
Javascript
// Function that prints perfect pyramid function perfectPyramid(str) { // To store length of string let n = str.length; // To store total elements in // a perticular row let x = 1; // To store total number elements // used upto that row let ele = 1; // To store total number of rows let rows = 0; // Loop to determine the rows and // elements upto which string is used while (ele <= n) { x += 2; ele += x; rows++; } // To travese the given string let ch = 0; // Nested loop to make the perfect // pyramid from given string for (let i = 1, k = 0; i <= rows; ++i, k = 0) { // Loop to print initial // spaces of every row for (let space = 1; space <= rows - i; ++space) { process.stdout.write( " " ); } // Loop to print character // of the string while (k != 2 * i - 1) { process.stdout.write(str[ch] + " " ); ++k; ch++; } process.stdout.write( "\n" ); } } // Driver code let str = "PyramidOfStrings" ; // Function call perfectPyramid(str); |
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; // Function that prints a perfect pyramid void printTriangle(string str) { int k = 0; // Loop to calculate spaces for ( int i = 0; i < str.length(); i++) { if (str.length() >= (i + 1) * (i + 1)) { k += 1; } } k -= 1; // Iterate over the length of the string and // print the substring and its repetition for ( int i = 0; i < str.length(); i++) { string spaces = " " ; // To remove the imperfect part if (str.length() < (i + 1) * (i + 1)) { break ; } // Calculate the size of spaces in each iteration spaces = string(k, ' ' ); // Print calculated spaces cout << spaces; k -= 1; // Print the triangle 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 { // Function that prints a perfect pyramid static void printTriangle(String str) { int k = 0 ; // Loop to calculate spaces for ( int i = 0 ; i * i < str.length(); i++) { k += 1 ; } k -= 1 ; // Iterate over the length of the string and // print the substring and its repetition for ( int i = 0 ; i < str.length(); i++) { String spaces = " " ; // To remove the imperfect part if (i * i >= str.length()) { break ; } // Calculate the size of spaces in each // iteration spaces = " " .repeat(k); // Calculate the start and end indices for // substring int start = i * i; int end = Math.min((i + 1 ) * (i + 1 ), str.length()); // Print calculated spaces System.out.print(spaces); k -= 1 ; // Print the triangle System.out.println(str.substring(start, end)); } } public static void main(String[] args) { String str = "PyramidOfStrings" ; printTriangle(str); } } |
Python3
# Python code to make a perfect # pyramid from a given string # Function that prints perfect pyramid def printTriangle( str ): k = 0 # loop to calculate spaces for i in range ( len ( str )): if ( len ( str ) > = (i + 1 ) * (i + 1 )): k + = 1 k - = 1 # Iterate over the length of the string and # print the substring and its repetition for i in range ( len ( str )): s = " " # To remove imperfect part if ( len ( str ) < (i + 1 ) * (i + 1 )): break # calculate the size of spaces in each iteartion s = s * k # print calculated spaces print (s,end = '') k - = 1 # Print the triangle print ( str [(i * i):(i + 1 ) * (i + 1 )]) # Driver Code if __name__ = = '__main__' : str = "PyramidOfStrings" printTriangle( str ) # This code is contributed by Susobhan Akhuli |
C#
using System; public class Program { // Function that prints perfect pyramid public static void PrintTriangle( string str) { int k = 0; // loop to calculate spaces for ( int i = 0; i < str.Length; i++) { if (str.Length >= (i + 1) * (i + 1)) { k += 1; } } k -= 1; // Iterate over the length of the string and // print the substring and its repetition for ( int i = 0; i < str.Length; i++) { string s = " " ; // To remove imperfect part if (str.Length < (i + 1) * (i + 1)) { break ; } // calculate the size of spaces in each iteartion s = new string ( ' ' , k); // print calculated spaces Console.Write(s); k -= 1; // Print the triangle 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 that prints perfect pyramid function printTriangle(str) { let k = 0; // loop to calculate spaces for (let i = 0; i < str.length; i++) { if (str.length >= (i + 1) * (i + 1)) { k += 1; } } k -= 1; // Iterate over the length of the string and // print the substring and its repetition for (let i = 0; i < str.length; i++) { let s = " " ; // To remove imperfect part if (str.length < (i + 1) * (i + 1)) { break ; } // calculate the size of spaces in each iteartion s = s.repeat(k); // print calculated spaces console.log(s, end= '' ); k -= 1; // Print the triangle console.log(str.slice(i * i, (i + 1) * (i + 1))); } } // Driver code let str = "PyramidOfStrings" ; printTriangle(str); |
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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!