LeetCode problem #6 — ZigZag Conversion (JavaScript)

H   O   R
E L T E E
L H
D     M     E
U N C L
N A A D
C R

Solution #1: Multi-dimensional array

In this solution, we loop through the input string’s letters, and store each one in a multi-dimensional array that visually represents the eventual ZigZag. We do this by keeping a couple of markers: currentRow and headingDown. What these two markers do, is they enable us to keep track of which row should get the next letter, and whether we should head up or down after processing that letter. Once we then head up or down, we check if we’ve exceeded the size of the ZigZag, and then flip to head in the other direction. In other words, we zig-zag through the string!

[
[ 'D', 'M', 'E' ],
[ 'U', 'N', 'C', 'L' ],
[ 'N', 'A', 'A', 'D' ],
[ 'C', 'R' ]
]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Duncan McArdle

Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.