We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Snail Traversal

Difficulty: Medium


Problem Description

Write code that enhances all arrays such that you can call the snail(rowsCount, colsCount) method that transforms the 1D array into a 2D array organized in the pattern known as snail traversal order. Invalid input values should output an empty array. If rowsCount * colsCount !== nums.length, the input is considered invalid.

Snail traversal order starts at the top left cell with the first value of the current array. It then moves through the entire first column from top to bottom, followed by moving to the next column on the right and traversing it from bottom to top. This pattern continues, alternating the direction of traversal with each column, until the entire current array is covered.

Key Insights

  • The transformation requires checking if the product of rowsCount and colsCount matches the length of the input array.
  • The traversal alternates between downward and upward movements in the columns.
  • The output must be formed into a 2D array that reflects this traversal order.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input array. Space Complexity: O(m * k), where m is rowsCount and k is colsCount (the size of the output 2D array).

Solution

To implement the solution:

  1. Validate the input by checking if rowsCount * colsCount equals the length of the input array. If not, return an empty array.
  2. Initialize a 2D array with the given dimensions.
  3. Loop through each column, filling it in alternating directions: top-to-bottom for even-indexed columns and bottom-to-top for odd-indexed columns.
  4. Return the populated 2D array.

Code Solutions

def snail(nums, rowsCount, colsCount):
    if rowsCount * colsCount != len(nums):
        return []

    result = [[0] * colsCount for _ in range(rowsCount)]
    index = 0

    for col in range(colsCount):
        if col % 2 == 0:  # Downward direction
            for row in range(rowsCount):
                result[row][col] = nums[index]
                index += 1
        else:  # Upward direction
            for row in range(rowsCount - 1, -1, -1):
                result[row][col] = nums[index]
                index += 1

    return result
← Back to All Questions