Skip to main content

Snail Traversal - Solution & Explanation

Medium11 min read
Practice this problem

Problem Statement

Write code that enhances all arrays such that you can call the snail(rowsCount, colsCount) method that transforms the 1D array into a 2D array organised in the pattern known as snail traversal order. Invalid input values should output an empty array. If rowsCount * colsCount !== nums.length, the input is considered invalid.

Snail traversal order starts at the top left cell with the first value of the current array. It then moves through the entire first column from top to bottom, followed by moving to the next column on the right and traversing it from bottom to top. This pattern continues, alternating the direction of traversal with each column, until the entire current array is covered. For example, when given the input array [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15] with rowsCount = 5 and colsCount = 4, the desired output matrix is shown below. Note that iterating the matrix following the arrows corresponds to the order of numbers in the original array.

 

Traversal Diagram

 

Example 1:

Input: 
nums = [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15]
rowsCount = 5
colsCount = 4
Output: 
[
 [19,17,16,15],
 [10,1,14,4],
 [3,2,12,20],
 [7,5,18,11],
 [9,8,6,13]
]

Example 2:

Input: 
nums = [1,2,3,4]
rowsCount = 1
colsCount = 4
Output: [[1, 2, 3, 4]]

Example 3:

Input: 
nums = [1,3]
rowsCount = 2
colsCount = 2
Output: []
Explanation: 2 multiplied by 2 is 4, and the original array [1,3] has a length of 2; therefore, the input is invalid.

 

Constraints:

  • 0 <= nums.length <= 250
  • 1 <= nums[i] <= 1000
  • 1 <= rowsCount <= 250
  • 1 <= colsCount <= 250

 

Approach Overview

Problem Overview: You are given a 1D array and a row count. The task is to convert it into a 2D matrix arranged in a snail traversal pattern: the first column fills from top to bottom, the next column from bottom to top, alternating direction for every column. If the array size cannot perfectly fill the matrix (rowsCount * colsCount != n), return an empty matrix.

Approach 1: Matrix Construction Using Snail Order with Iterative Filling (Time: O(n), Space: O(n))

Create a result matrix with rowsCount rows and colsCount = n / rowsCount columns. Iterate through the input array while tracking the current column index. For even-numbered columns, place values from top to bottom; for odd-numbered columns, place them from bottom to top. The direction flip creates the characteristic snail pattern. This approach relies on straightforward array traversal and explicit matrix construction. Each element is written exactly once, giving linear O(n) time and O(n) space for the output matrix. This is the most intuitive and readable implementation.

Approach 2: Two-Pointer Technique with Precomputed Indices (Time: O(n), Space: O(n))

Instead of switching traversal direction inside the matrix, compute the target row index mathematically. Maintain two pointers representing the top and bottom rows of the current column. For even columns, increment from the top pointer; for odd columns, decrement from the bottom pointer. Alternatively, derive the row using a formula like row = (col % 2 == 0) ? i % rowsCount : rowsCount - 1 - (i % rowsCount). This removes conditional iteration logic and treats placement as index mapping. The method uses ideas similar to two-pointer traversal and deterministic index calculation. Time complexity remains O(n) with O(n) space for the matrix.

Recommended for interviews: The iterative matrix construction approach is what most interviewers expect. It shows you can simulate traversal patterns clearly and handle matrix indexing without mistakes. The index-based two-pointer technique is slightly more mathematical and demonstrates deeper control over index mapping, but the simpler iterative version is usually easier to explain under interview pressure.

Approach 1: Matrix Construction Using Snail Order with Iterative Filling

This approach involves directly filling a 2D array using the input array nums by iterating over the columns in tandem with rows, alternating between top-down and bottom-up directions for each new column.

The key idea is to iterate over the given nums array, and fill the current column based on whether its index is even or odd. For even indices we fill from the top row to the bottom row; for odd indices, from the bottom row to the top row.

The algorithm involves:

  1. First verifying if the dimensions match.
  2. Initializing a 2D list for the result.
  3. Filling cells in the 2D result following alternating column traversal directions until the nums array is exhausted.

The C solution first checks if product of rows and columns equals the size of the nums array. It initializes a dynamic 2D array to store the resulting matrix. Using a loop, it fills each column in either top-to-bottom or bottom-to-top order depending on the current column index, incrementing through the nums array sequentially.

Code

C

Java

Python

JavaScript

C#

Complexity

Time Complexity: O(ROWS * COLS) as each element must be traversed once.
Space Complexity: O(ROWS * COLS) for storing the result matrix.

Try this approach in the editor →

Approach 2: Two-Pointer Technique with Precomputed Indices

This second approach draws on precomputing indices for traversing the nums array according to snail traversal rules using a two-pointer technique. Here, two pointers always mark top and bottom traversals of a given column.

In this strategy:

  1. Validate the input dimensions.
  2. Use two pointers moving from top to bottom and vice versa.
  3. Fill the multidimensional array by manually adjusting pointers for direction changes after completing each column entry.

The C++ solution uses vectors to dynamically allocate and manage the rows of matrices. With two pointers, iterating up or down depending on even or odd column indices results in efficient walking through each column without extra list operations.

Code

C++

C#

Complexity

Time Complexity: O(ROWS * COLS)
Space Complexity: O(ROWS * COLS) due to resulting vector matrix.

Try this approach in the editor →

Approach 3: Default Approach

Code

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Matrix Construction Using Snail Order with Iterative Filling

Time Complexity: O(ROWS * COLS) as each element must be traversed once.
Space Complexity: O(ROWS * COLS) for storing the result matrix.

Two-Pointer Technique with Precomputed Indices

Time Complexity: O(ROWS * COLS)
Space Complexity: O(ROWS * COLS) due to resulting vector matrix.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Matrix Construction Using Snail OrderO(n)O(n)Best general solution. Clear logic and easy to implement in interviews.
Two-Pointer Technique with Precomputed IndicesO(n)O(n)Useful when you want constant-direction iteration and index math instead of explicit direction switching.

Video Solution

2624. Snail Traversal - Leetcode Solution • Endeavour Monk • 1,043 views views

Watch 1 more video solutions →

Frequently Asked Questions

Is Snail Traversal easy or hard?
Snail Traversal is generally considered a medium difficulty problem. The core logic is simple, but off-by-one errors and incorrect row indexing are common pitfalls. Candidates who are comfortable with matrix indexing and traversal patterns typically solve it quickly.
How to solve Snail Traversal in O(n)?
Compute the number of columns as n / rowsCount. Then iterate through the array once while determining the target row based on the column direction. Even columns use row indices increasing from 0 to rowsCount-1, while odd columns use decreasing indices. This single pass achieves O(n) time.
What is the best approach for Snail Traversal?
The most practical approach constructs the matrix column by column while alternating direction. Even columns fill top-to-bottom and odd columns fill bottom-to-top. This simulation runs in O(n) time and uses O(n) space for the resulting matrix, making it both efficient and easy to implement in interviews.
What data structure is used in Snail Traversal?
The solution primarily uses arrays and a 2D matrix structure. The algorithm simulates traversal by controlling row indices and column direction, sometimes combined with pointer-style index calculations.
What is the time complexity of Snail Traversal?
Snail Traversal runs in O(n) time where n is the number of elements in the input array. Each value is placed into the matrix exactly once. The space complexity is O(n) because a new matrix of the same total size must be created.
Snail Traversal Python or Java solution approach?
Both Python and Java implementations follow the same idea: allocate a matrix with rowsCount rows and colsCount columns, then iterate through the input array while switching direction for every column. Each element is assigned once, resulting in O(n) time complexity.
Is Snail Traversal asked at Google, Amazon, or Meta?
Snail-style traversal and zigzag matrix filling patterns appear in interviews at companies like Amazon, Google, and Meta under matrix simulation problems. The exact problem may vary, but the concept of alternating traversal direction is commonly tested.

Ready to solve this problem?

Practice Snail Traversal with our built-in code editor and test cases.

Practice on FleetCode