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
1 row is identity
Single row
Empty
Zigzag with 3 rows
Zigzag with 4 rows
Algorithm Flow
Solution Approach
Simulate the zigzag traversal by placing each character into the appropriate row, moving down then up cyclically.
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
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();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
