medium Zigzag Conversion
Problem Statement
Given a string s and a numRows integer representing the number of rows, write the string in a zigzag pattern on the given number of rows and then read it line by line, and return the resultant string.
The zigzag pattern means writing characters in a diagonal down-and-up fashion. For example, given the string "HELLOPROGRAMMING" and 4 rows, the pattern would look like:
H R M
E P O M I
L O G A N
L R G
Reading it line by line gives us "HRMEPOMILOGANLRG".
Examples
Example 1:
- Input:
s = "HELLOPROGRAMMING", numRows = 4 - Expected Output:
"HRMEPOMILOGANLRG" - Explanation: The zigzag pattern is:
Reading line by line gives "HRMEPOMILOGANLRG".H R M E P O M I L O G A N L R G
Example 2:
- Input:
s = "PROBLEMCHALLENGE", numRows = 5 - Expected Output:
"PHRCAEOMLGBELNLE" - Explanation: The zigzag pattern is:
Reading line by line gives "LCCETEHLDELOEGAEEN".P H R C A E O M L G B E L N L E
Example 3:
- Input:
s = "ABCDE", numRows = 2 - Expected Output:
"ACEBD" - Explanation: The zigzag pattern is:
Reading line by line gives "ACEBD".A C E B D
Constraints:
- 1 <= s.length <= 1000
sconsists of English letters (lower-case and upper-case), ',' and '.'.- 1 <= numRows <= 1000
Try it yourself
Try solving this question here:
class Solution {
public String convert(String s, int numRows) {
// ToDo: Wrte Your Code Here.
return "";
}
}
✅ Solution Zigzag Conversion
Problem Statement
Given a string s and a numRows integer representing the number of rows, write the string in a zigzag pattern on the given number of rows and then read it line by line, and return the resultant string.
The zigzag pattern means writing characters in a diagonal down-and-up fashion. For example, given the string "HELLOPROGRAMMING" and 4 rows, the pattern would look like:
H R M
E P O M I
L O G A N
L R G
Reading it line by line gives us "HRMEPOMILOGANLRG".
Examples
Example 1:
- Input:
s = "HELLOPROGRAMMING", numRows = 4 - Expected Output:
"HRMEPOMILOGANLRG" - Explanation: The zigzag pattern is:
Reading line by line gives "HRMEPOMILOGANLRG".H R M E P O M I L O G A N L R G
Example 2:
- Input:
s = "PROBLEMCHALLENGE", numRows = 5 - Expected Output:
"PHRCAEOMLGBELNLE" - Explanation: The zigzag pattern is:
Reading line by line gives "LCCETEHLDELOEGAEEN".P H R C A E O M L G B E L N L E
Example 3:
- Input:
s = "ABCDE", numRows = 2 - Expected Output:
"ACEBD" - Explanation: The zigzag pattern is:
Reading line by line gives "ACEBD".A C E B D
Constraints:
- 1 <= s.length <= 1000
sconsists of English letters (lower-case and upper-case), ',' and '.'.- 1 <= numRows <= 1000
Solution
To solve this problem, we need to create the zigzag pattern and then read the characters row by row. We can use an array of strings to store characters for each row. By iterating through the input string, we place each character in the appropriate row and switch direction (up or down) whenever we reach the top or bottom row. This approach ensures we correctly form the zigzag pattern. After forming the pattern, we concatenate the strings from each row to get the final result.
This method is effective because it simulates the actual zigzag writing process and uses a direct and intuitive approach to manage the character placement. It is also efficient in terms of both time and space complexity.
Step-by-Step Algorithm
-
Edge Case Handling:
- If
numRowsis 1, return the input string as is because there's no zigzag pattern possible with one row.
- If
-
Initialize Rows:
- Create an array of empty strings (or StringBuilder objects) to hold characters for each row. The number of elements in this array should be equal to
numRows.
- Create an array of empty strings (or StringBuilder objects) to hold characters for each row. The number of elements in this array should be equal to
-
Set Direction:
- Initialize variables
currentRowto 0 andgoingDowntoFalse. These will help in tracking the current row being filled and the direction of filling (down or up).
- Initialize variables
-
Place Characters:
- Iterate through each character in the input string
s:- Append the character to the current row.
- If
currentRowis 0 (top row) orcurrentRowisnumRows - 1(bottom row), change the direction (togglegoingDown). - Move to the next row based on the current direction (
goingDown). IfgoingDownisTrue, incrementcurrentRow. IfgoingDownisFalse, decrementcurrentRow.
- Iterate through each character in the input string
-
Concatenate Rows:
- After iterating through all characters, join all the strings (or contents of StringBuilder objects) from each row to form the final zigzag string.
Algorithm Walkthrough
Using the input s = "HELLOPROGRAMMING", numRows = 4:
-
Edge Case Handling:
numRowsis 4, not 1, so we proceed.
-
Initialize Rows:
rows = ["", "", "", ""]
-
Set Direction:
currentRow = 0goingDown = False
-
Place Characters:
-
Iterate through the string "HELLOPROGRAMMING":
-
'H':
rows[0] = "H"currentRow = 1goingDown = True
-
'E':
rows[1] = "E"currentRow = 2goingDown = True
-
'L':
rows[2] = "L"currentRow = 3goingDown = True
-
'L':
rows[3] = "L"currentRow = 2goingDown = False
-
'O':
rows[2] = "LO"currentRow = 1goingDown = False
-
'P':
rows[1] = "EP"currentRow = 0goingDown = False
-
'R':
rows[0] = "HR"currentRow = 1goingDown = True
-
'O':
rows[1] = "EPO"currentRow = 2goingDown = True
-
'G':
rows[2] = "LOG"currentRow = 3goingDown = True
-
'R':
rows[3] = "LR"currentRow = 2goingDown = False
-
'A':
rows[2] = "LOGA"currentRow = 1goingDown = False
-
'M':
rows[1] = "EPOM"currentRow = 0goingDown = False
-
'M':
rows[0] = "HRM"currentRow = 1goingDown = True
-
'I':
rows[1] = "EPOMI"currentRow = 2goingDown = True
-
'N':
rows[2] = "LOGAN"currentRow = 3goingDown = True
-
'G':
rows[3] = "LRG"currentRow = 2goingDown = False
-
-
-
Concatenate Rows:
- Join all rows to form the final zigzag string:
result = "HRM" + "EPOMI" + "LOGAN" + "LRG"result = "HRMEPOMILOGANLRG"
- Join all rows to form the final zigzag string:
Code
class Solution {
public String convert(String s, int numRows) {
// Edge case: if there's only one row, return the string as is
if (numRows == 1) return s;
// Create an array of StringBuilder objects to hold rows
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
rows[i] = new StringBuilder();
}
// Initialize variables to track the current row and direction
int currentRow = 0;
boolean goingDown = false;
// Iterate through each character in the string
for (char c : s.toCharArray()) {
// Append the character to the current row
rows[currentRow].append(c);
// Change direction at the first and last rows
if (currentRow == 0 || currentRow == numRows - 1) {
goingDown = !goingDown;
}
// Move to the next row based on the direction
currentRow += goingDown ? 1 : -1;
}
// Combine all rows to form the final result
StringBuilder result = new StringBuilder();
for (StringBuilder row : rows) {
result.append(row);
}
return result.toString();
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.convert("HELLOPROGRAMMING", 4)); // HRMEPOMILOGANLRG
System.out.println(solution.convert("PROBLEMCHALLENGE", 5)); // PHRCAMLOEBLNGLEN
System.out.println(solution.convert("ABCDE", 2)); // ACEBD
}
}
Complexity Analysis
Time Complexity
The time complexity of the algorithm is
Space Complexity
The space complexity of the algorithm is
🤖 Don't fully get this? Learn it with Claude
Stuck on Zigzag Conversion? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Zigzag Conversion** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Zigzag Conversion** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Zigzag Conversion**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Zigzag Conversion**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.