Zigzag Pattern Text Conversion

medium string simulation

Problem

Take a string and write its characters into numRows rows in a zigzag — go down to the bottom, then diagonally back up to the top, repeating. After laying out the characters, read each row left to right and concatenate. Maintain one buffer per row; when the placement row hits 0 or numRows − 1, flip the direction.

Inputs = "PAYPALISHIRING", numRows = 3
Output"PAHNAPLSIIGYIR"
Row 0: P A H N. Row 1: A P L S I I G. Row 2: Y I R.

def convert(s, num_rows):
    if num_rows == 1:
        return s
    rows = [""] * num_rows
    r, d = 0, 1
    for ch in s:
        rows[r] += ch
        if r == 0:
            d = 1
        elif r == num_rows - 1:
            d = -1
        r += d
    return "".join(rows)
function convert(s, numRows) {
  if (numRows === 1) return s;
  const rows = Array.from({ length: numRows }, () => "");
  let r = 0, dir = 1;
  for (const ch of s) {
    rows[r] += ch;
    if (r === 0) dir = 1;
    else if (r === numRows - 1) dir = -1;
    r += dir;
  }
  return rows.join("");
}
class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1) return s;
        StringBuilder[] rows = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) rows[i] = new StringBuilder();
        int r = 0, dir = 1;
        for (char ch : s.toCharArray()) {
            rows[r].append(ch);
            if (r == 0) dir = 1;
            else if (r == numRows - 1) dir = -1;
            r += dir;
        }
        StringBuilder out = new StringBuilder();
        for (StringBuilder row : rows) out.append(row);
        return out.toString();
    }
}
string convert(string s, int numRows) {
    if (numRows == 1) return s;
    vector<string> rows(numRows);
    int r = 0, dir = 1;
    for (char ch : s) {
        rows[r] += ch;
        if (r == 0) dir = 1;
        else if (r == numRows - 1) dir = -1;
        r += dir;
    }
    string out;
    for (auto& row : rows) out += row;
    return out;
}
Time: O(n) Space: O(n)