ZigZag conversion

Write the characters down the rows and diagonally back up in a zigzag, then read the result off row by row.

Time O(n)Space O(n)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

A direction flag tracks whether the current row index is moving down or diagonally back up. It flips only when the top row or the bottom row is reached, which is exactly what traces out the zigzag shape without ever computing coordinates.

Code

public static string Convert(string s, int numRows) {
    var rows = new StringBuilder[numRows];
    for (int i = 0; i < numRows; i++) rows[i] = new StringBuilder();
    int cur = 0, dir = -1;
    foreach (char c in s) {
        rows[cur].Append(c);
        if (cur == 0 || cur == numRows - 1) dir = -dir;
        cur += dir;
    }
    return string.Concat(rows);
}

Tips

In the .NET library

The row index never needs the character's column position: dir alone decides whether the next character goes one row down or one row up.