Zigzag Grid Traversal With Skip - Problem

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

Input & Output

Example 1 — Basic 2x3 Grid
$ Input: grid = [[1,2,3],[4,5,6]]
Output: [1,3,5]
💡 Note: Zigzag traversal: 1→2→3, then 6→5→4. With skipping: take positions 0,2,4 which are values 1,3,5
Example 2 — Single Row
$ Input: grid = [[1,2,3,4]]
Output: [1,3]
💡 Note: Only one row, traverse left to right: 1→2→3→4. Skip alternates: take positions 0,2 which are 1,3
Example 3 — Single Column
$ Input: grid = [[1],[2],[3]]
Output: [1,3]
💡 Note: Zigzag on single column: 1 (pos 0), 2 (pos 1), 3 (pos 2). Take even positions: 1,3

Constraints

  • 1 ≤ m, n ≤ 100
  • 1 ≤ grid[i][j] ≤ 1000

Visualization

Tap to expand
Zigzag Grid Traversal With Skip INPUT 2D Grid (m x n) 1 2 3 4 5 6 R0 R1 C0 C1 C2 grid = [[1,2,3], [4,5,6]] Zigzag Pattern: Row 0: Left --> Right Row 1: Right --> Left (Skip every alternate cell) ALGORITHM STEPS 1 Start at (0,0) Visit cell[0][0] = 1 2 Skip (0,1), Visit (0,2) Skip 2, visit cell = 3 3 Drop to Row 1 Traverse Right to Left 4 Skip (1,2), Visit (1,1) Skip 6, visit cell = 5 1 2 3 4 5 6 Visited Skipped FINAL RESULT Collected Values in Order: 1 (0,0) 3 (0,2) 5 (1,1) Output: [1, 3, 5] OK - Complete! 3 cells visited out of 6 Skip pattern maintained Zigzag order preserved Time: O(m*n), Space: O(1) Key Insight: Track position with a counter that increments for each cell. Visit only when counter is even (0, 2, 4...). Alternate row direction: even rows go left-to-right, odd rows go right-to-left. Direct skip avoids extra storage. TutorialsPoint - Zigzag Grid Traversal With Skip | Direct Skip During Traversal Approach
Asked in
Microsoft 25 Amazon 20 Google 15
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen