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: 1D Array → 2D Matrix1234Input: [1,2,3,4]Transform1423Col 0: ↓Col 1: ↑Result: [[1,4],[2,3]]
Understanding the Visualization
1
Input Array
Linear array [1,2,3,4] with dimensions 2×2
2
Snail Pattern
Fill columns alternately: down, up, down, up...
3
2D Result
Matrix [[1,4],[2,3]] following snail pattern
Key Takeaway
🎯 Key Insight: Even-indexed columns fill downward, odd-indexed columns fill upward, creating the snail pattern
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