6. Zigzag Conversion
Asked at 16Bloomberg60Amazon58Google54Microsoft49Meta45Apple22PayPal100Zopsmart100Infosys45Zoho81PayPay68Siemens65Walmart Labs60Oracle55Salesforce49tcs27
Problem
Write s in a zigzag over numRows rows (down the rows, then diagonally back up, repeatedly), then read the rows top to bottom and return the result.
Example: s = "PAYPALISHIRING", numRows = 3 → "PAHNAPLSIIGYIR" (rows PAHN, APLSIIG, YIR)
Simulate writing the zigzag: keep one buffer per row and a cursor that moves down, bounces at the last row, moves up, bounces at row 0. Reading the rows top to bottom gives the answer.
"PAYPALISHIRING", numRows = 4 cursor: 0 1 2 3 2 1 0 1 2 3 ...
row 0: P I N
row 1: A L S I G
row 2: Y A H R
row 3: P I
-> "PIN" + "ALSIG" + "YAHR" + "PI"
Complexity: O(n).
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
rows = [[] for _ in range(numRows)]
r, step = 0, 1
for ch in s:
rows[r].append(ch)
if r == 0:
step = 1
elif r == numRows - 1:
step = -1
r += step
return "".join("".join(row) for row in rows)
assert Solution().convert("PAYPALISHIRING", 3) == "PAHNAPLSIIGYIR"
assert Solution().convert("PAYPALISHIRING", 4) == "PINALSIGYAHRPI"
assert Solution().convert("A", 1) == "A"
assert Solution().convert("AB", 1) == "AB"
assert Solution().convert("ABC", 2) == "ACB"
class Solution {
public 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 r = 0, step = 1;
for (char c : s.toCharArray()) {
rows[r].append(c);
if (r == 0) step = 1;
else if (r == numRows - 1) step = -1;
r += step;
}
StringBuilder out = new StringBuilder();
for (StringBuilder row : rows) out.append(row);
return out.toString();
}
}
func convert(s string, numRows int) string {
if numRows == 1 || numRows >= len(s) {
return s
}
rows := make([][]byte, numRows)
r, step := 0, 1
for i := 0; i < len(s); i++ {
rows[r] = append(rows[r], s[i])
if r == 0 {
step = 1
} else if r == numRows-1 {
step = -1
}
r += step
}
var sb strings.Builder
for _, row := range rows {
sb.Write(row)
}
return sb.String()
}