mediumStringArrays & Hashing

Zigzag Conversion

mediumTime: O(n)Space: O(n)

Recognize the pattern

write string in zigzag across rowsread row by rowoscillating row index

Brute force idea

Build a 2D grid — O(n × numRows) space.

Better approach

Array of strings (one per row). Walk through string assigning each char to its row. Row bounces: 0→numRows-1→0→... O(n).

Key invariant

The row index oscillates between 0 and numRows-1. Each character appends to its row's string. Concatenating all rows gives the result.

Watch out for

Edge case: numRows = 1 → return the original string. No zigzag needed.

Arrays & Hashing Pattern