AlgoViz

Pattern 11

Easy

Alternating 1/0 triangle

Problem

Print a binary triangle where each row starts with 1,0,1,… and alternates for a given size n.

In simple words

Use one loop for the rows and another for what goes in each row to draw the shape.

The idea

The triangle shape again, with the printed character alternating. Notice that whether a cell is 1 or 0 depends on the parity of row + column, so you can compute it directly instead of tracking a toggle.

The trick

  • Start each row with 1 when the row index is odd, 0 when even.
  • Equivalently: the cell is 1 when (i + j) is even.
rows5

Step 1 of 7. Binary triangle: each row alternates 1s and 0s, starting with 1 on odd rows. rows 5.

1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// 13// 0 14// 1 0 15// 0 1 0 16// 1 0 1 0 17 8for i in 1..n:9  start = (i odd) ? 1 : 010  for j in 1..i: print(start); start = 1 - start

Input

grid
5 × 5

Memory

rows
5

Output

printed rows
rows
5

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Example

Input:
n = 5
Output:
1 / 0 1 / 1 0 1 / 0 1 0 1 / 1 0 1 0 1

Finished the walkthrough? Add it to your streak.