Print a Zero-One Triangle
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given
n, return n rows of a right triangle filled with alternating 1s and 0s: row i has i values separated by single spaces, odd rows start with 1, even rows start with 0, and values alternate along each row.
The pattern is a parityParityWhether a number is even or odd, usually tested with % 2. exercise in disguise — the value in a cell depends only on whether its row number plus column number is even. The second solution trades that formula for a running bit that flips after every cell.
Test Case 1:
Input:n = 4
Output:["1", "0 1", "1 0 1", "0 1 0 1"]
Explanation:Values alternate 1 and 0 along each row, and neighbouring rows start with opposite values — like a checkerboard.
Test Case 2:
Input:n = 1
Output:["1"]
Explanation:The first row always starts with 1.
Constraints
- ◆
1 ≤ n ≤ 20
Try the Dry Run
Approach & Solutions
Parity of Row Plus ColumnGood
Number rows and columns from 1. The cell at row i, column j holds 1 when i + j is even and 0 when it is odd. That single rule produces the checkerboard: moving one step along a row, or one row down, flips the parity. Values in a row are separated by single spaces.
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printZeroOneTriangle(int n) {
String[] result = new String[n];
for (int i = 1; i <= n; i++) {
StringBuilder row = new StringBuilder();
for (int j = 1; j <= i; j++) {
int bit = (i + j) % 2 == 0 ? 1 : 0;
row.append(j == 1 ? "" : " ").append(bit);
}
result[i - 1] = row.toString();
}
return result;
}
}Flip a Bit as You GoOptimal
Only the first value of a row needs thought: odd rows start with 1 and even rows with 0, which is exactly i % 2. After that, every value is the opposite of the one before it, so flip the bit with bit = 1 − bit after writing it.
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printZeroOneTriangle(int n) {
String[] result = new String[n];
for (int i = 1; i <= n; i++) {
StringBuilder row = new StringBuilder();
int bit = i % 2;
for (int j = 1; j <= i; j++) {
row.append(j == 1 ? "" : " ").append(bit);
bit = 1 - bit;
}
result[i - 1] = row.toString();
}
return result;
}
}