Created
October 22, 2025 19:48
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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