Step 01 Beginner Problems — Patterns
Pattern 11 — Binary Number Triangle Pattern
A growing triangle filled with alternating 0s and 1s. Each row starts with 1 if it is an even row and 0 if it is odd, then flips at every step across the row — a chessboard rule folded into a triangle.
1 0 1 1 0 1 0 1 0 1 1 0 1 0 1
How to think about it
Number the rows i = 0, 1, ..., n-1 and the columns within a row j = 0, 1, ..., i. The entry at (i, j) is 1 when i + j is even and 0 when i + j is odd — equivalently, the entry flips every time you move one step right or one step down. Row i therefore starts with 1 for even i and 0 for odd i, then alternates. You can compute each entry from the parity of i + j, or carry a 'current bit' variable that toggles after every print; both produce the same figure.
Code
The code picks the row's starting bit from the row parity (1 if i is even, else 0) and then generates (start + j) % 2 for each column j — adding j flips the bit back and forth across the row. No state is carried between rows; each row is recomputed from its own indices.
def pattern(n):
for i in range(n):
start = 1 if i % 2 == 0 else 0
bits = [str((start + j) % 2) for j in range(i + 1)]
print(" ".join(bits))Key points
- Entry (i, j) = 1 if i + j is even, else 0 — one parity rule generates the whole figure.
- Row i starts with 1 when i is even and 0 when i is odd.
- Within a row the bits strictly alternate; a repeated bit means a bug.
- Parity thinking (n % 2) is the entire engine — no counters or memory needed.
- Edge case n = 1 prints just '1'.