Algorithm Day102 - Zigzag Conversion
🧩 Problem Description
LeetCode 6 - Zigzag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows, like this:
1 | P A H N |
Then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows.
Example:
1 | Input: s = "PAYPALISHIRING", numRows = 3 |
💡 First Thought (Simulation)
We can simulate the zigzag process by writing characters row by row.
Keep track of the current row and the direction (down or up).
⚙️ Optimized Approach — Row Buckets
We maintain a list of StringBuilder objects, one for each row,
and iterate over the string while changing direction when we hit the top or bottom row.
Java Code
1 | public class Solution { |
⏱️ Complexity Analysis
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Iterate over string | O(n) | O(n) |
🧠 Key Takeaways
- Zigzag pattern can be simulated by tracking row direction.
- Great example of string traversal with controlled direction change.
- Easy to visualize and implement with
StringBuilder[].
📘 Next Step: We’ll look into string pattern transformation problems in the next post.