1202. Rail Fence Unscramble
A message was hidden by writing it in a zigzag over rails rows: the first letter goes on rail 0, the next ones go down to the last rail, then back up, so the rail of index i repeats with period 2 * (rails - 1). The scrambled cipher is obtained by reading rail 0 left to right, then rail 1, and so on down to the last rail.
Return the original message. Count how many letters each rail receives from the period, cut cipher into rails, and replay the zigzag to rebuild the message. If rails == 1 or rails >= cipher.length, nothing is scrambled and cipher is returned unchanged.
Here 1 <= cipher.length <= 2 * 10^5, 1 <= rails <= 2 * 10^5, and cipher uses lowercase letters. The whole job takes O(n) time and O(n) space.
Example 1
- Input:
- cipher = "maedohetthbigtngtetrei", rails = 3
- Output:
- "meetatthebridgetonight"
- Explanation:
The note was written in a zigzag over 3 rails; rebuilding the zigzag from the rail contents restores the message.
Example 2
- Input:
- cipher = "rttoehnettearaln", rails = 4
- Output:
- "rotatethelantern"
- Explanation:
With 4 rails the zigzag period is 6; slicing the cipher by rail counts and replaying the zigzag restores the message.
Example 3
- Input:
- cipher = "abc", rails = 1
- Output:
- "abc"
- Explanation:
With one rail nothing is scrambled, so the cipher is returned unchanged.
Constraints
1 ≤ cipher.length ≤ 2 * 105
1 ≤ rails ≤ 2 * 105
cipher contains lowercase letters only
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)