Taro Logo

Zigzag Conversion

#161 Most AskedMedium
0 views
Topics:
Strings

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 <= 1000
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • 1 <= numRows <= 1000

Solution


Clarifying Questions

When 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:

  1. What should be returned if `numRows` is 1 or greater than the length of the string `s`?
  2. Can the input string `s` be empty or null, and if so, should we return an empty string?
  3. What character set does `s` contain? Are we restricted to standard ASCII characters, or should we account for Unicode/multibyte characters?
  4. Is case sensitivity important, or should the characters maintain their exact case from the input string?
  5. Should we optimize for time complexity or space complexity, or is an $O(N)$ solution using extra space for rows acceptable?

Brute Force Solution

Approach

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:

  1. Start by drawing a large grid with as many rows as requested and enough columns to hold all the letters.
  2. Take the first letter of the word and place it at the very top of the first column.
  3. Move straight down the first column, placing the next letters into the rows below until you reach the bottom row.
  4. Once at the bottom, start moving diagonally upwards and to the right, placing the remaining letters one by one into the appropriate rows until you reach the top row again.
  5. Repeat this up-and-down motion, weaving through the grid, until every single letter has been placed in its designated spot.
  6. Leave any empty spaces in the grid blank.
  7. Finally, read the grid from left to right, starting from the top row and moving down to the bottom row, gathering all the letters to form your final converted string.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n) – Building the grid requires iterating through each of the n characters in the input string exactly once to place them into their respective row positions. Afterward, reading the rows from top to bottom to assemble the final string requires visiting all n placed characters again. This process performs a constant amount of work per character across both steps, resulting in approximately 2 * n total operations. Dropping the constant factor simplifies the final time complexity to O(n).
Space Complexity
O(N) – To construct the zigzag pattern described in the steps, we utilize a collection of strings or dynamic lists representing each of the requested rows to store the characters as we weave through them. Every single character from the input string of length N is eventually placed into one of these row structures, meaning the total characters stored across all rows equals N. Therefore, these intermediate row lists act as our auxiliary data structure, consuming extra memory that grows linearly with the input size N. Combining the rows from top to bottom at the end requires negligible additional storage, so the overall space complexity simplifies to Big O of N.

Optimal Solution

Approach

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:

  1. Check if the requested number of rows is just one, in which case the letters do not need to change at all and you can keep them as they are.
  2. Set up a separate holding area for each row where we can collect letters that belong together.
  3. Begin moving through the original string of letters from the very first character to the very last.
  4. Drop the current letter into the holding area corresponding to the row where it naturally lands on our zigzag path.
  5. Keep track of our vertical direction, moving downwards row by row until we hit the very bottom row.
  6. Once we reach the bottom, reverse direction and start moving upwards row by row until we hit the very top again.
  7. Repeat this falling and rising motion, placing each incoming letter into its matching row holding area until every letter has been processed.
  8. Combine the contents of all the row holding areas, starting from the top row and moving down to the bottom row, to reveal the final rearranged result.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n) – As we iterate through the input string of length n character by character, each character is placed into its respective row holding area in constant time. After processing all n characters, we concatenate the rows together, which also touches each of the n characters once. This results in roughly 2n total operations as we visit every character during both the distribution and collection phases. By dropping the constant factor of 2, the overall time complexity simplifies to O(n).
Space Complexity
O(n) – The algorithm creates separate holding areas, represented as row strings or lists, which collectively store all the characters from the input string. Since every character from the input of size N is placed into these row buckets, the total extra memory consumed scales linearly with the input length. Combining the contents of these holding areas to form the final result requires an auxiliary string of size N to store the rearranged output. Therefore, the total auxiliary space complexity simplifies to Big O of N, where N is the length of the input string.

Edge Cases

numRows is equal to 1
How to Handle:
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
How to Handle:
Return the original string as each character will simply occupy its own distinct row.
Empty string input
How to Handle:
Return an empty string right away to prevent out of bounds errors or unnecessary computations.
String length is smaller than numRows
How to Handle:
Populate only the available rows up to the string length and return the concatenated result.
Maximum length strings with large numRows
How to Handle:
Use a linear time traversal algorithm with string builders to ensure optimal scaling and avoid memory overhead.
String with all identical characters
How to Handle:
The row tracking logic correctly groups and constructs the output string without any grouping anomalies.
numRows is 2
How to Handle:
Alternate character placement strictly between row 0 and row 1 until the entire string is processed.
0/257 completed