S3Q2 · Print Pattern - N Shape¶
⚡ Quick Reference
Type: Full I/O - pattern printing
Core idea: each row has | on both sides with \ moving one step right each row. Row i has i-1 spaces before \ and n-i spaces after.
Key rules:
- | on both sides of every row
- \ at position i within the inner area (1-indexed)
- Leading spaces before \: i - 1
- Trailing spaces after \ (before closing |): n - i
- No trailing spaces after the final |
Problem Statement¶
Problem (I/O type)
Given n, print an N-shaped pattern. | appears on both sides of every row, and \ moves diagonally from top-left to bottom-right.
Examples:
3
|\ |
| \ |
| \|
2
|\ |
| \|
Deriving the pattern¶
For n=3, the inner area between the | bars has width n:
Row 1: | \ · · | leading=0, trailing=2
Row 2: | · \ · | leading=1, trailing=1
Row 3: | · · \ | leading=2, trailing=0
Row i |
Leading spaces | Trailing spaces |
|---|---|---|
| 1 | i-1 = 0 |
n-i = 2 |
| 2 | i-1 = 1 |
n-i = 1 |
| 3 | i-1 = 2 |
n-i = 0 |
Row structure: | + (i-1) spaces + \ + (n-i) spaces + |
The trailing spaces (between \ and |) are inside the pattern - they're needed to keep the right | properly aligned.
No trailing spaces after the closing |
The problem says no spaces to the right of the pattern. The spaces inside the bars are part of the pattern. The closing | is always the last character - nothing follows it.
Tracing n = 3¶
| i | i-1 spaces |
\ |
n-i spaces |
Row |
|---|---|---|---|---|
| 1 | `` | \ |
·· |
|\··| |
| 2 | · |
\ |
· |
|·\·| |
| 3 | ·· |
\ |
`` | |··\| |
(dots = spaces)
Solution approaches¶
Edge case: n = 1¶
i=1: leading=0, trailing=0 → | + + `\` + + | = |\|
Key takeaways¶
Diagonal \ at row i: leading = i-1
The backslash moves one step right per row. At row i (1-indexed), it has i-1 spaces before it and n-i spaces after - both decreasing and increasing symmetrically.
Spaces inside bars are part of the pattern
The trailing spaces between \ and the closing | keep the right bar aligned. They're inside the pattern, not trailing whitespace - so they must stay.
Always escape backslash: \\
In Python strings, \ is an escape character. Write "\\" to get a literal backslash in output. In f-strings, place "\\" outside the braces.