Java String Program · S38
Zigzag Conversion in Java
Write the characters down the rows, then diagonally back up, and repeat. Reading the rows from top to bottom gives the converted string.
Problem Statement
Write the characters of a string in a zigzag pattern over numRows rows: down from the first row to the last, then diagonally up to the first, and so on. Return the rows read from top to bottom.
If numRows is 1, or at least the length of the string, the string is returned unchanged.
Input/Output Examples
"JAVABYTECHIE", rows = 3Output"JBCAAYEHEVTI"Explanation: row 0 holds J B C, row 1 holds A A Y E H E, row 2 holds V T I."HELLOWORLD", rows = 4Output"HOEWRLOLLD"Explanation: the pattern repeats every 6 characters."ABC", rows = 1Output"ABC"Explanation: with one row there is no zigzag.Visual Explanation
- Row 0charsJBCindexes 0, 4, 8
- Row 1charsAAYEHEindexes 1, 3, 5, 7, 9, 11
- Row 2charsVTIindexes 2, 6, 10
- Donejoin rows 0, 1, 2"JBCAAYEHEVTI"
"JAVABYTECHIE" over 3 rows: characters go down rows 0, 1, 2, then up to row 1, then down again. Reading row by row gives the result.The row index moves 0, 1, 2, 1, 0, 1, 2, …, so the whole pattern repeats every 2 × (numRows - 1) characters. Both solutions are built on that cycle.
Approaches
The first approach simulates the zigzag. The second computes directly which indexes belong to each row.
Approach 1: Simulate the Rows (Recommended)
Idea: keep one StringBuilder per row and move a row pointer down and up while appending characters.
- Create
numRowsbuilders. - Append each character to the current row.
- Reverse direction at the top and bottom rows.
- Concatenate the rows.
Time: O(n) · Space: O(n).
Approach 2: Cycle Index Formula
Idea: with cycle = 2 × (numRows - 1), row r takes index start + r and, for middle rows, also start + cycle - r.
- Loop over the rows from 0 to
numRows - 1. - For each cycle start, append the "down" character
start + row. - For middle rows, also append the "up" character
start + cycle - rowif it exists.
Time: O(n) · Space: O(n). Only the output is stored; no per-row builders.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Simulate the Rows (Recommended)
Mirrors the drawing exactly, which makes it easy to explain and to debug.
public class ZigzagRows {
// Walks down and up the rows, appending each character to its row
static String convert(String s, int numRows) {
if (numRows == 1 || numRows >= s.length()) {
return s;
}
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
rows[i] = new StringBuilder();
}
int row = 0;
int step = 1;
for (char c : s.toCharArray()) {
rows[row].append(c);
if (row == 0) {
step = 1; // bounce off the top
} else if (row == numRows - 1) {
step = -1; // bounce off the bottom
}
row += step;
}
StringBuilder result = new StringBuilder(s.length());
for (StringBuilder r : rows) {
result.append(r);
}
return result.toString();
}
public static void main(String[] args) {
Object[][] cases = {{"JAVABYTECHIE", 3}, {"HELLOWORLD", 4}, {"ABC", 1}};
for (Object[] c : cases) {
System.out.println("\"" + c[0] + "\", rows=" + c[1] + " -> \"" + convert((String) c[0], (Integer) c[1]) + "\"");
}
}
}
"JAVABYTECHIE", rows=3 -> "JBCAAYEHEVTI" "HELLOWORLD", rows=4 -> "HOEWRLOLLD" "ABC", rows=1 -> "ABC"
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Cycle Index Formula
Each character is appended exactly once, directly in its final position.
public class ZigzagCycle {
// The pattern repeats every 2 * (numRows - 1) characters; read each row by index
static String convert(String s, int numRows) {
if (numRows == 1 || numRows >= s.length()) {
return s;
}
int cycle = 2 * (numRows - 1);
StringBuilder result = new StringBuilder(s.length());
for (int row = 0; row < numRows; row++) {
for (int start = 0; start + row < s.length(); start += cycle) {
result.append(s.charAt(start + row)); // the "down" character
int diagonal = start + cycle - row;
if (row != 0 && row != numRows - 1 && diagonal < s.length()) {
result.append(s.charAt(diagonal)); // the "up" character
}
}
}
return result.toString();
}
public static void main(String[] args) {
Object[][] cases = {{"JAVABYTECHIE", 3}, {"HELLOWORLD", 4}, {"ABC", 1}};
for (Object[] c : cases) {
System.out.println("\"" + c[0] + "\", rows=" + c[1] + " -> \"" + convert((String) c[0], (Integer) c[1]) + "\"");
}
}
}
"JAVABYTECHIE", rows=3 -> "JBCAAYEHEVTI" "HELLOWORLD", rows=4 -> "HOEWRLOLLD" "ABC", rows=1 -> "ABC"
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Simulate the Rows | O(n) | O(n) |
| Cycle Index Formula | O(n) | O(n) |
Here n is the length of the string. Both approaches place every character once; the output itself needs n characters.
Interview Tips and Recommended Approach
- Handle one row first. With
numRows = 1the cycle is 0, which would break the formula. - Draw a small example. Sketching 3 or 4 rows makes the cycle length obvious.
- Only middle rows have a second character per cycle. The top and bottom rows are visited once per cycle.
- Know the reverse problem. Rebuilding the original string from the zigzag output uses the same index formula.
Recommended Approach: Simulate the Rows
Why: it follows the pattern literally, so it is hard to get wrong under pressure, and it still runs in linear time.