Snail Traversal - Problem
Snail Traversal Matrix Transformation
You need to enhance JavaScript arrays with a special method called
๐ How Snail Traversal Works:
โข Start at the top-left corner with the first array element
โข Fill the entire first column from top to bottom
โข Move to the second column and fill from bottom to top
โข Continue alternating direction for each column until all elements are placed
Example: Array
Invalid Input: Return an empty array
You need to enhance JavaScript arrays with a special method called
snail(rowsCount, colsCount) that transforms a 1D array into a 2D matrix following a unique "snail traversal" pattern.๐ How Snail Traversal Works:
โข Start at the top-left corner with the first array element
โข Fill the entire first column from top to bottom
โข Move to the second column and fill from bottom to top
โข Continue alternating direction for each column until all elements are placed
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:19 8 1 6
10 5 17 13
3 2 16 11
7 1 14 20
9 17 12 4
โ โ 15Invalid Input: Return an empty array
[] if rowsCount ร colsCount โ array.length Input & Output
example_1.js โ Basic 3ร4 Matrix
$
Input:
arr = [1,2,3,4,5,6,7,8,9,10,11,12], rowsCount = 3, colsCount = 4
โบ
Output:
[[1,6,7,12],[2,5,8,11],[3,4,9,10]]
๐ก Note:
Column 0: [1,2,3] (top-to-bottom), Column 1: [6,5,4] (bottom-to-top), Column 2: [7,8,9] (top-to-bottom), Column 3: [12,11,10] (bottom-to-top)
example_2.js โ Single Row
$
Input:
arr = [1,2,3,4], rowsCount = 1, colsCount = 4
โบ
Output:
[[1,2,3,4]]
๐ก Note:
With only one row, all elements are placed in the same row, alternating columns but same position
example_3.js โ Invalid Dimensions
$
Input:
arr = [1,2,3], rowsCount = 3, colsCount = 2
โบ
Output:
[]
๐ก Note:
3 ร 2 = 6, but array length is 3. Since 6 โ 3, return empty array
Visualization
Tap to expand
Understanding the Visualization
1
Start at Top-Left
Begin placing elements in the first column from top to bottom
2
Alternate Directions
Move to next column and fill from bottom to top
3
Continue Pattern
Keep alternating direction for each subsequent column
4
Complete Matrix
All elements are placed following the snail traversal pattern
Key Takeaway
๐ฏ Key Insight: Use modular arithmetic to determine column direction - even columns (0,2,4...) go top-to-bottom, odd columns (1,3,5...) go bottom-to-top.
Time & Space Complexity
Time Complexity
O(n)
Single pass through input array with constant time position calculations
โ Linear Growth
Space Complexity
O(rowsCount ร colsCount)
Space needed to store the output 2D matrix
โก Linearithmic Space
Constraints
- 1 โค arr.length โค 250
- 1 โค rowsCount, colsCount โค 250
- arr contains distinct integers from 1 to arr.length
- Must implement as Array.prototype.snail method
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code