Zigzag Conversion
01 · Problem
Imagine writing the characters of a string s in a zigzag across numRows rows: you go down row by row from the top row to the bottom row, then diagonally up row by row back to the top, then down again, and so on. For example, with numRows = 3 the characters ABCDEFG are laid out as:
A E
B D F
C G
After placing every character, read the rows from top to bottom, each row left to right, and concatenate them. Return that string ("AEBDFCG" in the example above).
If numRows is 1, or is at least the length of s, the zigzag never turns and the result equals s.
02 · Examples
s = "ABCDEFGHIJ", numRows = 3
"AEIBDFHJCG"
Rows are "AEI", "BDFHJ" and "CG". Concatenating them gives "AEIBDFHJCG".
s = "ABCDEFGHIJ", numRows = 4
"AGBFHCEIDJ"
Rows are "AG", "BFH", "CEI" and "DJ". Concatenating them gives "AGBFHCEIDJ".
s = "HELLO", numRows = 1
"HELLO"
With a single row there is no zigzag, so the string is unchanged.
03 · Constraints
- 011 <= s.length <= 1000
- 02s consists of English letters (upper and lower case), ',' and '.'
- 031 <= numRows <= 1000
04 · Optimal complexity
- Time
- O(n)
- Space
- O(n)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.