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 INPUT Zigzag Pattern (numRows = 3) Row 0: Row 1: Row 2: P A Y P A L I S H Input Values s = "PAYPALISHIRING" numRows = 3 Row Arrays Structure rows[0], rows[1], rows[2] [ ] [ ] [ ] ALGORITHM STEPS 1 Initialize Row Arrays Create numRows empty strings 2 Traverse String Track direction: down/up 3 Assign Characters Add char to current row 4 Concatenate Rows Join all row strings Row Arrays After Filling rows[0]: P A H N rows[1]: A P L S I I G rows[2]: Y I R Direction toggles at row 0 and row 2 FINAL RESULT Concatenate all rows: P A H N + A P L S I I G + Y I R = "PAHNAPLSIIGYIR" OK - Result Verified Length: 14 characters Time: O(n) | Space: O(n) Key Insight: Use row arrays to collect characters. Track current row index and direction (down/up). Toggle direction when reaching row 0 or row (numRows-1). Finally join all rows for result. Pattern: 0 --> 1 --> 2 --> 1 --> 0 --> 1 --> 2 ... (zigzag movement) TutorialsPoint - Zigzag Conversion | Row Arrays Approach
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