Code Logo

Zigzag Conversion

Published at25 Jul 2026
Hard 2 views
Like0

Given a string s and an integer numRows, convert the string into a zigzag pattern across numRows rows and return the result read row by row.

For example, "PAYPALISHIRING" with 3 rows produces P A H N on row 0, A P L S I I G on row 1, Y I R on row 2, reading as "PAHNAPLSIIGYIR". With 4 rows, the same input produces "PINALSIGYAHRPI".

The zigzag conversion simulates writing text in a zigzag pattern across multiple rows, like a snake moving down and up. It tests your ability to simulate a pattern-based traversal without constructing a 2D grid.

The solution creates an array of strings for each row and iterates through the input, placing each character in the appropriate row. The row index moves down (incrementing) then up (decrementing) in a cycle.

Edge cases include numRows = 1 (return the string unchanged), an empty string (return ""), and numRows >= string length (return the string unchanged as no zigzag is formed).

Example Input & Output

Example 1
Input
"AB",1
Output
"AB"
Explanation

1 row is identity

Example 2
Input
"A",1
Output
"A"
Explanation

Single row

Example 3
Input
"",3
Output
""
Explanation

Empty

Example 4
Input
"PAYPALISHIRING",3
Output
"PAHNAPLSIIGYIR"
Explanation

Zigzag with 3 rows

Example 5
Input
"PAYPALISHIRING",4
Output
"PINALSIGYAHRPI"
Explanation

Zigzag with 4 rows

Algorithm Flow

Recommendation Algorithm Flow for Zigzag Conversion

Solution Approach

Simulate the zigzag traversal by placing each character into the appropriate row, moving down then up cyclically.

function convert(s, numRows)
  if numRows == 1 then return s
  rows = array of numRows empty strings
  row = 0, down = true
  for i = 0 to length(s) - 1
    rows[row] = rows[row] + s[i]
    if down then row = row + 1 else row = row - 1
    if row == 0 or row == numRows - 1 then down = not down
  return join(rows, "")

Handle the single-row case. Create rows array. Start at row 0 moving down. For each character, append it to the current row. When reaching the top or bottom, reverse direction. Finally, concatenate all rows into one string.

Time complexity is O(n), space complexity is O(n).

Best Answers

java
class Solution {
    public String solution(String s, int n) {
        if(n==1||n>=s.length())return s;
        StringBuilder[] rows=new StringBuilder[n];
        for(int i=0;i<n;i++)rows[i]=new StringBuilder();
        int cur=0;boolean d=false;
        for(int i=0;i<s.length();i++){
            rows[cur].append(s.charAt(i));
            if(cur==0||cur==n-1)d=!d;
            cur+=d?1:-1;
        }StringBuilder r=new StringBuilder();
        for(StringBuilder sb:rows)r.append(sb);
        return r.toString();
    }
}