Zigzag Conversion
Algorithm/String
Intuition
The problem involves rearranging a string into a zigzag pattern across a given number of rows and then reading the pattern row by row. To efficiently build the zigzag pattern, we simulate the row traversal by switching direction between top-to-bottom and bottom-to-top. Each character is placed in the appropriate row during traversal, and the rows are later joined to form the final result.
Approach
Below is the step-by-step breakdown of the approach:
- Edge Case Handling:
- If the number of rows is 1 or greater than the string length, return the input string directly as no transformation is needed.
- Initialize Data Structures:
- Create an array
record
of sizenumRows
, with each element initialized to an empty string. This array will store the characters for each row. - Use a boolean flag
ascending
to track the direction of movement (either down or up the rows). - Initialize a
curRow
variable to keep track of the current row being filled.
- Create an array
- Iterate Through the Characters:
- Traverse the input string, placing each character in the appropriate row of
record
based on the current direction. - Adjust the
curRow
value:- If moving down, increment
curRow
. - If moving up, decrement
curRow
.
- If moving down, increment
- Switch directions whenever the first row (
curRow === 0
) or the last row (curRow === numRows - 1
) is reached.
- Traverse the input string, placing each character in the appropriate row of
- Join the Rows:
- After all characters are placed, concatenate all rows from
record
to form the final result string.
- After all characters are placed, concatenate all rows from
Complexity
- Time Complexity: , where
n
is the length of the input string. Each character is processed exactly once. - Space Complexity: , since we store all characters in the
record
array.