Back to Interview Prep

Warm Up · Star Pattern

Alternating 1s and 0s (Global Toggle)

Problem Statement

Write a program to print a triangle of alternating 1s and 0s, but the toggle continues globally across rows.

Output

1
01
010
1010

Approach

  • Global Toggle Variable: Declare toggle = 1 before the outer loop.
  • Outer Loop: Loop i from 0 to n - 1.
  • Inner loop: Loop j from 0 to i. On each iteration, append toggle to the row string and flip it (1 -> 0, 0 -> 1).
  • Print the Row: After the inner loop.

Time & Space Complexity

Time Complexity: O(n^2)

Space Complexity: O(n) per row.

Explanation

  • Key difference: in the Right-Angled Triangle of Alternating 1s and 0s, toggle = 1 was reset at the start of every row. Here the toggle is declared once, so it keeps alternating across the entire pattern.

Your solution

Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.

// Write your solution in JavaScript
// Print the answer with console.log()


Console

No output yet. Use console.log() to print values here.

Write your own solution and press Submit once to unlock the answer.

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in