Zigzag Conversion
mediumStrings II+20 XPTime limit 2s
Write a message in a zigzag over k rows: go straight down the rows, then diagonally back up to the top row, then down again, and so on. Then read the rows from top to bottom, left to right. With k = 3, PLACEMENTDRIVE is written as
P E T V
L C M N D I E
A E R
and read as PETV + LCMNDIE + AER = PETVLCMNDIEAER. With k = 1 the message is unchanged.
Input:
- line 1: the message (letters, no spaces)
- line 2:
k
Output: the message read row by row from the zigzag.
Constraints: 1 ≤ length ≤ 10⁵, 1 ≤ k ≤ 1000.
Think about it: you don't need a grid. Either append each character to its row while a direction variable bounces between the top and bottom rows, or use the pattern: the zigzag repeats every 2k − 2 characters, the top and bottom rows take one character per cycle, and every middle row r takes two (at offsets r and 2k − 2 − r).
Sample input 1
PLACEMENTDRIVE 3
Sample output 1
PETVLCMNDIEAER
Sample input 2
SKILLS 1
Sample output 2
SKILLS
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).