The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
Example 3:
Input: s = "A", numRows = 1 Output: "A"
Constraints:
1 <= s.length <= 1000s consists of English letters (lower-case and upper-case), ',' and '.'.1 <= numRows <= 1000When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a string of letters that you need to write down in a zigzag pattern across multiple rows and then read across. The brute force approach involves actually building a giant grid on a page, placing every single letter into its exact zigzag position one by one, and then reading the rows to get your final answer.
Here's how the algorithm would work step-by-step:
def convert(input_string, num_rows):
if num_rows == 1 or num_rows >= len(input_string):
return input_string
# We initialize a 2D matrix representing the grid to physically place characters
num_columns = len(input_string)
grid_matrix = [['' for col in range(num_columns)] for row in range(num_rows)]
current_row = 0
current_col = 0
going_down_flag = False
for char_index, character in enumerate(input_string):
grid_matrix[current_row][current_col] = character
# We change direction at the top or bottom boundaries to create the zigzag weave
if current_row == 0 or current_row == num_rows - 1:
going_down_flag = not going_down_flag
if going_down_flag:
current_row += 1
else:
current_row -= 1
current_col += 1
# We collect characters row by row from left to right to form the final output
result_characters = []
for row_list in grid_matrix:
for character in row_list:
if character != '':
result_characters.append(character)
return ''.join(result_characters)Instead of physically moving letters up, down, and diagonally on a grid, the optimal approach simply collects and sorts the characters by following their natural vertical path from top to bottom and back up. We can think of this as creating separate empty buckets for each horizontal row and dropping each letter into the correct bucket as we travel down and up the page.
Here's how the algorithm would work step-by-step:
def convert(input_string, num_rows):
# Single row requires no rearrangement since characters keep their original order.
if num_rows == 1:
return input_string
row_holding_areas = [[] for _ in range(num_rows)]
current_row_index = 0
moving_downward = False
for character in input_string:
row_holding_areas[current_row_index].append(character)
# Reverse traversal direction upon hitting top or bottom boundaries.
if current_row_index == 0 or current_row_index == num_rows - 1:
moving_downward = not moving_downward
if moving_downward:
current_row_index += 1
else:
current_row_index -= 1
# Combine row holding areas sequentially from top to bottom into final string.
return "".join("".join(row) for row in row_holding_areas)| Case | How to Handle |
|---|---|
| numRows is equal to 1 | Return the original string immediately since no zigzag pattern can be formed with a single row. |
| numRows is greater than or equal to the length of the string | Return the original string as each character will simply occupy its own distinct row. |
| Empty string input | Return an empty string right away to prevent out of bounds errors or unnecessary computations. |
| String length is smaller than numRows | Populate only the available rows up to the string length and return the concatenated result. |
| Maximum length strings with large numRows | Use a linear time traversal algorithm with string builders to ensure optimal scaling and avoid memory overhead. |
| String with all identical characters | The row tracking logic correctly groups and constructs the output string without any grouping anomalies. |
| numRows is 2 | Alternate character placement strictly between row 0 and row 1 until the entire string is processed. |