Taro Logo

Zigzag Grid Traversal With Skip

Easy
Asked by:
Tata Consultancy Services
0 views
Topics:
Arrays

You are given an m x n 2D array grid of positive integers.

Your task is to traverse grid in a zigzag pattern while skipping every alternate cell.

Zigzag pattern traversal is defined as following the below actions:

  • Start at the top-left cell (0, 0).
  • Move right within a row until the end of the row is reached.
  • Drop down to the next row, then traverse left until the beginning of the row is reached.
  • Continue alternating between right and left traversal until every row has been traversed.

Note that you must skip every alternate cell during the traversal.

Return an array of integers result containing, in order, the value of the cells visited during the zigzag traversal with skips.

Example 1:

Input: grid = [[1,2],[3,4]]

Output: [1,4]

Explanation:

Example 2:

Input: grid = [[2,1],[2,1],[2,1]]

Output: [2,1,2]

Explanation:

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]]

Output: [1,3,5,7,9]

Explanation:

Constraints:

  • 2 <= n == grid.length <= 50
  • 2 <= m == grid[i].length <= 50
  • 1 <= grid[i][j] <= 2500

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 the input grid is empty or null?
  2. Could you clarify the exact meaning of "skipping every alternate cell"? For example, if we visit index 0, do we skip index 1 and visit index 2 on the same row, and does the skip continue across row boundaries or restart on each row?
  3. Are the grid dimensions guaranteed to be equal (i.e., $N \times N$), or can it be a rectangular grid ($M \times N$) with varying numbers of rows and columns?
  4. What are the data types and value ranges of the integers inside the grid?
  5. When we reverse direction on odd rows (right-to-left), does the skipping pattern also reverse its origin relative to the new traversal direction?

Brute Force Solution

Approach

To solve this problem using the brute force approach, we simply follow the exact zigzag path through the grid from start to finish. We visit every single cell one by one while keeping track of our journey by collecting every other item we encounter.

Here's how the algorithm would work step-by-step:

  1. Begin at the very top left corner of the grid.
  2. Move across the first row step by step until you reach the opposite side, writing down every single item you pass along the way.
  3. Drop down to the next row below, and now travel in the exact opposite direction, walking backward while continuing to write down the items you encounter.
  4. Repeat this back and forth pattern, moving down one row at a time and switching directions with each new row, until you have walked through every corner of the grid.
  5. Look over everything you wrote down during your entire journey.
  6. Cross off every second item from your list, starting with the very first one you collected.
  7. Read through the remaining items in the exact order you kept them to find the final result.

Code Implementation

def zigzag_grid_traversal_with_skip(grid):
    collected_items = []

    # Flatten the grid into a single alternating path by reversing every other row
    for row_index in range(len(grid)):
        current_row = grid[row_index]
        if row_index % 2 != 0:
            current_row = current_row[::-1]

        for item in current_row:
            collected_items.append(item)

    result_items = []

    # Filter the path by skipping every second item starting from the very first one
    for item_index in range(len(collected_items)):
        if item_index % 2 == 0:
            result_items.append(collected_items[item_index])

    return result_items

Big(O) Analysis

Time Complexity
O(n * m) – To traverse the entire grid of n rows and m columns, we must visit every single cell once by walking back and forth along each row. Collecting all the items into a list takes time proportional to the total number of cells, which is n multiplied by m. Afterward, filtering out every second item requires a single linear pass over the collected list containing n * m elements. Combining the traversal and the filtering, the total operations approximate n * m + (n * m) / 2, which simplifies to the final Big O time complexity of O(n * m).
Space Complexity
O(R * C) – The brute force approach requires a temporary list to store every single item visited along the zigzag path, where N represents the total number of elements in the grid of size R by C. As we traverse the grid row by row, this collection grows to hold all R times C elements. A second auxiliary list or filtered result is then created to store the remaining items after crossing off every second element, which also scales proportionally with N. Therefore, the auxiliary data structures scale linearly with the total number of elements in the grid.

Optimal Solution

Approach

This solution traverses a 2D grid in a zigzag pattern from top to bottom. Even rows are traversed from left to right, while odd rows are traversed from right to left. During the entire continuous traversal, every alternate cell is collected starting with the initial top-left cell.

Here's how the algorithm would work step-by-step:

  1. Initialize an empty list to store the picked cell values and a boolean flag to track whether to include the next cell.
  2. Loop through each row index of the grid from top to bottom.
  3. Determine the traversal order of the row, keeping it unchanged for even rows and reversing it for odd rows.
  4. Iterate through the cells in the determined row order.
  5. Append the cell value to the result list if the include flag is true, then toggle the flag for the next cell.
  6. Return the accumulated list of values after completing all rows.

Code Implementation

def zigzag_traversal(grid):
    result = []
    include_current = True
    # Iterate through each row index in the grid
    for row_index in range(len(grid)):
        current_row = grid[row_index]
        # Reverse row elements for odd-indexed rows to achieve zigzag order
        row_values = current_row if row_index % 2 == 0 else current_row[::-1]
        # Traverse the ordered row values and pick every alternate element
        for value in row_values:
            if include_current:
                result.append(value)
            include_current = not include_current
    return result

Big(O) Analysis

Time Complexity
O(m * n) – Each of the m rows with n columns is processed exactly once, resulting in total linear work proportional to the total number of cells in the grid.
Space Complexity
O(m * n) – The output list holds up to half of all cells from the grid, which uses linear auxiliary space relative to the number of cells.

Edge Cases

Empty grid or null input where rows or columns equal zero
How to Handle:
Check for null or empty dimensions at the start and return an empty array immediately.
Single cell grid with dimensions one by one
How to Handle:
The traversal loop executes once, correctly capturing the single element without any out of bounds errors.
Grid with a single row and multiple columns
How to Handle:
The row index remains zero, meaning it only traverses left to right while correctly applying the skip logic.
Grid with a single column and multiple rows
How to Handle:
Alternating directions still evaluate correctly per row, visiting every alternate row and cell as required.
Large grid dimensions pushing memory limits near maximum constraints
How to Handle:
The algorithm processes the grid iteratively with a single output list, maintaining optimal linear space and time complexity.
Grid containing negative numbers, zeros, and extreme boundary integer values
How to Handle:
Since the task is traversal rather than arithmetic aggregation, numerical values are simply appended directly without risk of overflow.
Grid with alternating row lengths or ragged arrays
How to Handle:
The loop bounds check each specific row length before accessing elements to prevent index out of bounds exceptions.
Grid where the skip pattern causes all elements in odd rows to be bypassed
How to Handle:
The step increment of two handles the skip pattern uniformly across both directions without skipping entire rows unintentionally.