139. Zigzag Writer

A sign painter writes the text s on a board that has rows lines. The first letter goes on the top line, and every next letter goes one line lower, until the bottom line is reached. Then the painter climbs back up one line per letter to the top line, and keeps bouncing between the top and the bottom line like this until the text ends.

When the board is finished, read it line by line, from the top line to the bottom line, each line from left to right, and join everything into one string. Return that string. If there is only one line, or at least as many lines as letters, the text stays unchanged.

Example 1

Input:
s = "ABCDEFGHIJKLM", rows = 3
Output:
"AEIMBDFHJLCGK"
Explanation:

The lines hold AEIM, BDFHJL and CGK, so the answer is AEIMBDFHJLCGK.

Example 2

Input:
s = "sunrise", rows = 4
Output:
"seusnir"
Explanation:

The lines hold se, us, ni and r, which read as seusnir.

Constraints

1 ≤ s.length ≤ 105

1 ≤ rows ≤ 1000

s contains English letters, digits, spaces and punctuation

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…