Print a Mirrored Number Triangle
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given
n (at most 9), return the mirror image of the Increasing Number Triangle: n right-aligned rows where row i shows the digits from i down to 1.
A mirror imageMirror ImageThe shape flipped left-to-right: what was on the left is now on the right, and sequences read in reverse. flips two things at once — the row moves to the right edge (leading spaces) and its contents read backwards. Because the total width is always n, the rows line up on the right.
Test Case 1:
Input:n = 4
Output:[" 1", " 21", " 321", "4321"]
Explanation:The Increasing Number Triangle seen in a mirror: right-aligned, with the digits running from i down to 1.
Test Case 2:
Input:n = 2
Output:[" 1", "21"]
Explanation:One leading space on the first row, none on the second.
Constraints
- ◆
1 ≤ n ≤ 9
Try the Dry Run
Approach & Solutions
Nested Loops — Count Down from iGood
Row i has n − i leading spaces (to right-align it) followed by the digits i, i − 1, …, 1. Mirroring a row reverses both its position (left becomes right) and its order (counting up becomes counting down).
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printMirroredNumberTriangle(int n) {
String[] result = new String[n];
for (int i = 1; i <= n; i++) {
StringBuilder row = new StringBuilder();
for (int s = 0; s < n - i; s++) {
row.append(' ');
}
for (int j = i; j >= 1; j--) {
row.append(j);
}
result[i - 1] = row.toString();
}
return result;
}
}Put Each New Digit in FrontOptimal
Each row's digits are the previous row's digits with the new digit i placed in front: "1", "21", "321", … Keep that string and pad it on the left with n − i spaces. C writes the falling digits straight into a space-filled row.
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printMirroredNumberTriangle(int n) {
String[] result = new String[n];
String digits = "";
for (int i = 1; i <= n; i++) {
digits = i + digits;
result[i - 1] = " ".repeat(n - i) + digits;
}
return result;
}
}