Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created October 22, 2025 19:48
Show Gist options
  • Save mustafadalga/89e99da8a6dc6b30bf2620ac4cc46fdb to your computer and use it in GitHub Desktop.
Save mustafadalga/89e99da8a6dc6b30bf2620ac4cc46fdb to your computer and use it in GitHub Desktop.
Convert a string into a 2D array representing its zigzag pattern for given number of rows.
function stringToZigzagGrid(text: string, numRows: number): string[][] | string {
if (numRows < 2) return text
const grid: string[][] = Array.from({ length: numRows }, () => [])
let row = 0, col = 0, direction = "down"
for (let index = 0; index < text.length; index++) {
grid[row][col] = text[index]
if (row === numRows - 1) {
direction = "up"
} else if (row === 0) {
direction = "down"
}
if (direction === "down") {
row++
} else {
col++
row--
for (let r = 0; r < numRows; r++) {
if (!grid[r][col]) grid[r][col] = " ";
}
}
}
return grid
}
console.log(stringToZigzagGrid("PAYPALISHIRING", 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment