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 = 1before the outer loop. - Outer Loop: Loop
ifrom0ton - 1. - Inner loop: Loop
jfrom0toi. On each iteration, appendtoggleto 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 = 1was 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.