Zigzag Conversion - Problem
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
P A H N
A P L S I I G
Y I RAnd then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows.
Input & Output
Example 1 — Basic Case
$
Input:
s = "PAYPALISHIRING", numRows = 3
›
Output:
"PAHNAPLSIIGYIR"
💡 Note:
Characters form zigzag: Row 0 gets P,A,H,N; Row 1 gets A,P,L,S,I,I,G; Row 2 gets Y,I,R. Reading rows gives PAHNAPLSIIGYIR.
Example 2 — More Rows
$
Input:
s = "PAYPALISHIRING", numRows = 4
›
Output:
"PINALSIGYAHRPI"
💡 Note:
With 4 rows: Row 0: P,I,N; Row 1: A,L,S,I,G; Row 2: Y,A,H,R; Row 3: P,I. Result: PINALSIGYAHRPI.
Example 3 — Single Row
$
Input:
s = "A", numRows = 1
›
Output:
"A"
💡 Note:
With only 1 row, no zigzag pattern is formed. String remains unchanged.
Constraints
- 1 ≤ s.length ≤ 1000
- s consists of English letters (a-z), ',' and '.'
- 1 ≤ numRows ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
String "PAYPALISHIRING" with numRows = 3
2
Zigzag Pattern
Write characters in down-up-down zigzag
3
Output
Read each row left to right
Key Takeaway
🎯 Key Insight: The zigzag pattern repeats every 2*(numRows-1) characters, allowing efficient character distribution or mathematical calculation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code