Zigzag Grid Traversal With Skip - Problem
Imagine you're navigating through a 2D grid following a specific zigzag pattern, but with a twist - you must skip every alternate cell during your journey!
Given an m x n 2D array grid of positive integers, your task is to traverse the grid in a zigzag pattern while collecting values from only every other cell you encounter.
Zigzag Traversal Rules:
- π Start at the top-left corner
(0, 0) - β‘οΈ Move right across the first row until you reach the end
- β¬οΈ Drop down to the next row
- β¬ οΈ Move left across this row until you reach the beginning
- π Continue alternating between right and left traversal for each row
- βοΈ Skip every alternate cell during the entire traversal
Return an array containing the values of the cells you visit (not skip) in the order you encounter them.
Input & Output
example_1.py β Basic 3x3 Grid
$
Input:
grid = [[1,2,3],[6,5,4],[7,8,9]]
βΊ
Output:
[1,3,5]
π‘ Note:
Zigzag order: 1β2β3β6β5β4β7β8β9. With skipping alternates: positions 0,2,4 give us [1,3,5]
example_2.py β 2x4 Rectangle Grid
$
Input:
grid = [[1,2,3,4],[8,7,6,5]]
βΊ
Output:
[1,3,8,6]
π‘ Note:
Zigzag order: 1β2β3β4β5β6β7β8. Taking positions 0,2,4,6 gives us [1,3,5,7]. Wait, let me recalculate: 1β2β3β4β8β7β6β5, so [1,3,8,6]
example_3.py β Single Row Edge Case
$
Input:
grid = [[1,2,3,4,5]]
βΊ
Output:
[1,3,5]
π‘ Note:
Single row traversal left-to-right: 1β2β3β4β5. Taking alternate positions 0,2,4 gives us [1,3,5]
Visualization
Tap to expand
Understanding the Visualization
1
Start Top-Left
Begin at position (0,0) with counter = 0
2
Read First Line LeftβRight
Move right across first row, collecting at even positions
3
Drop to Next Line
Move down to second row, continue position counter
4
Read Second Line RightβLeft
Move left across second row, still collecting at even positions
5
Continue Pattern
Alternate row directions until complete
Key Takeaway
π― Key Insight: Use a single position counter across the entire zigzag traversal to determine which cells to collect, making it a clean O(mΓn) single-pass solution
Time & Space Complexity
Time Complexity
O(m Γ n)
Visit each cell exactly once in the grid
β Linear Growth
Space Complexity
O(k)
Where k is the number of collected elements (roughly half of total elements)
β Linear Space
Constraints
- m == grid.length
- n == grid[i].length
- 1 β€ m, n β€ 104
- 1 β€ grid[i][j] β€ 105
- The grid will always have at least one element
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code