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   R

And 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
Zigzag Conversion: "PAYPALISHIRING" → zigzag patternStep 1: Write in Zigzag PatternPAHNAPLSYIRStep 2: Read Row by RowRow 0: P A H NRow 1: A P L S I I GRow 2: Y I RFinal Result:PAHNAPLSIIGYIR
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
Asked in
Microsoft 25 Amazon 20 Google 15
167.0K Views
Medium Frequency
~15 min Avg. Time
3.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen