Code Logo

Zigzag Conversion

Published at25 Jul 2026
Hard 0 views
Like0

Convert a string to zigzag pattern on a given number of rows and read it row by row. The string is written in a zigzag pattern across the specified number of rows, then read line by line.

For example, "PAYPALISHIRING" with 3 rows becomes:
P A H N
A P L S I I G
Y I R
Reading row by row gives "PAHNAPLSIIGYIR".

Simulate the zigzag by tracking the current row and direction. Move down until hitting the last row, then move up until hitting the first row. Append each character to the appropriate row's buffer.

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
Recommendation Algorithm Flow for Zigzag Conversion

Solution Approach

function solution(s, numRows) {
  if (numRows === 1 || numRows >= s.length) return s;
  var rows = [];
  for (var i = 0; i < numRows; i++) rows[i] = '';
  var cur = 0, down = false;
  for (var i = 0; i < s.length; i++) {
    rows[cur] += s.charAt(i);
    if (cur === 0 || cur === numRows - 1) down = !down;
    cur += down ? 1 : -1;
  }
  return rows.join('');
}

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();
    }
}