Snail Traversal - Problem

Write code that transforms a 1D array into a 2D array organized in snail traversal order.

Snail traversal pattern:

  • Start at top-left with first array element
  • Fill entire first column from top to bottom
  • Move to next column and fill from bottom to top
  • Continue alternating direction for each column
  • Return empty array if rowsCount * colsCount !== nums.length

Example: Array [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15] with rowsCount = 5, colsCount = 4 becomes a 5×4 matrix where column 0 fills top→bottom, column 1 fills bottom→top, etc.

Input & Output

Example 1 — Basic Snail Pattern
$ Input: nums = [1,2,3,4], rowsCount = 2, colsCount = 2
Output: [[1,4],[2,3]]
💡 Note: Column 0: fill top-down [1,2]. Column 1: fill bottom-up [4,3]. Result matrix: [[1,4],[2,3]]
Example 2 — Invalid Dimensions
$ Input: nums = [1,2,3], rowsCount = 1, colsCount = 4
Output: []
💡 Note: 1 × 4 = 4 ≠ 3 (array length), so input is invalid. Return empty array.
Example 3 — Single Column
$ Input: nums = [1,2,3], rowsCount = 3, colsCount = 1
Output: [[1],[2],[3]]
💡 Note: Only one column (even), fill top-down: [[1],[2],[3]]

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ rowsCount ≤ 1000
  • 1 ≤ colsCount ≤ 1000

Visualization

Tap to expand
Snail Traversal INPUT nums = [1, 2, 3, 4] 1 2 3 4 idx 0 idx 1 idx 2 idx 3 Parameters: rowsCount = 2 colsCount = 2 Validation: 2 x 2 = 4 Length matches - OK Target: 2x2 matrix ? ? ? ? ALGORITHM STEPS 1 Create 2D Array Initialize rowsCount x colsCount 2 Col 0: Top to Bottom Fill [0,0]=1, [1,0]=2 3 Col 1: Bottom to Top Fill [1,1]=3, [0,1]=4 4 Return Result Matrix filled in snail order Snail Fill Pattern: 1 4 2 3 Col 0 Col 1 FINAL RESULT 2D Matrix Output: 1 4 2 3 [0] [1] [0] [1] Output: [[1, 4], [2, 3]] Verification: Row 0: [1, 4] - OK Row 1: [2, 3] - OK OK Key Insight: The snail traversal fills columns alternately: odd columns go top-to-bottom, even columns go bottom-to-top. Use index calculation: row = (col % 2 == 0) ? idx % rows : rows - 1 - (idx % rows) to determine position. Always validate: if rowsCount * colsCount !== nums.length, return empty array immediately. TutorialsPoint - Snail Traversal | Sequential Fill Approach
Asked in
Google 25 Meta 18 Amazon 15
28.4K Views
Medium Frequency
~15 min Avg. Time
892 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