Practice › Basics
Palindromic Number Pyramid
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print a pyramid with n rows. Row i (1-based) has n − i spaces, then the digits 1 2 … i … 2 1 written next to each other (no spaces between them). Do not print spaces after the digits. For n = 3:
1
121
12321
Input
A single integer n.
Output
The pyramid, n lines.
Constraints
- 1 ≤ n ≤ 9
For each row: print the spaces, then count up from 1 to i, then count down from i − 1 to 1.
Example 1
Input
3
Output
1 121 12321
Example 2
Input
1
Output
1
Hints
- Row i has n − i leading spaces.
- Then count up 1 … i and back down i − 1 … 1.
- Print nothing after the last digit.
Approach
Two nested loops per row: one for the spaces, then one going up and one going down for the digits. Because n ≤ 9 every number is a single digit, so the digits sit next to each other and the rows line up into a pyramid.
Complexity: O(n²) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
string row(n - i, ' ');
for (int d = 1; d <= i; d++) row += char('0' + d);
for (int d = i - 1; d >= 1; d--) row += char('0' + d);
cout << row << "\n";
}
return 0;
}Python solution
n = int(input())
for i in range(1, n + 1):
up = "".join(str(d) for d in range(1, i + 1))
print(" " * (n - i) + up + up[-2::-1])Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
for (int s = 0; s < n - i; s++) sb.append(' ');
for (int d = 1; d <= i; d++) sb.append(d);
for (int d = i - 1; d >= 1; d--) sb.append(d);
sb.append('\n');
}
System.out.print(sb);
}
}Solve Palindromic Number Pyramid online · All practice problems