Skip to content
Decoder

Zigzag Conversion

Medium

Problem

Write the characters of s across rows rows in a zigzag: the first character goes on row 0, the next on row 1, and so on down to the last row, then the path turns and goes back up one row at a time to row 0, then down again, until the string runs out. Return the rows read one after another, top row first.

For s = "ABCDEFGH" and rows = 3 the zigzag looks like this:

Example 1

A       E

Example 2

  B   D   F   H

Example 3

    C       G

Example 4

Input
s = "ABCDEFGH", rows = 3
Output
"AEBDFHCG"

Example 5

Input
s = "ABCDEFGH", rows = 2
Output
"ACEGBDFH"

Example 6

Input
s = "ABCDEFGH", rows = 1
Output
"ABCDEFGH"

Constraints

  • 1 <= s.length <= 1000
  • 1 <= rows <= 1000
  • s contains English letters, digits, , and ..

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.