"Snake" style solution for cyclically rotating array in LeetCode problem

"Snake" style solution for cyclically rotating array in LeetCode problem

This is a medium level task. However, accepted <50% contributed solutions.

In my opinion, it's good train for working with array and pointers to solve problems like that on LeetCode

You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k.

The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:

A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction.

Constraints:

  • m == grid.length

  • n == grid[i].length

  • 2 <= m, n <= 50

  • Both m and n are even integers.

  • 1 <= grid[i][j] <= 5000

  • 1 <= k <= 109

There is some catch, "leetcode-guys", included test case with:

Let's start analyze and decomposition:

  1. For rotation "layer", one of simple way - convert each layer into separate array.

  2. Rotation for array = slice shift. If the number "k" of rotation steps is more than the length of the array layer, we can use modulus (% in Python).

  3. Need algorithm for interpreter given "grid" array structure to single array for each layer.

When I started solve this problem, I image each layer as a Snake.

Where for 1 first Snake [1,2,3,4] -> [4,2,3,1] elements this head.

Next neck [16,14,15,13]

Then body [12,11,10,9]

Final tail [8,7,6,5]

For understanding, how much snakes in "grid", use minimal integer after floor division height and width. Because array 4*3 will have only one layer(snake). Or array 2 rows 1001 columns = one layer. Or 5*5 = only two and etc.

Next step, how to organize code structure.

Note: I used some extra variables and usen't lambda fucn for better explanation.

In main loop, the best way using processing each layer /snake/.

Let's start from head to tail:

Let's rotate snake, but before, calc modulus steps, because we don't want to rotate array like hamster in the wheel.

* ** Probably you know effective approach for this, pls share in comments.

And, finally, set "cursor" on the current array/snake/ and update elements in the main "grid" array.

And final iterate tmp in our "nloop":

Advices:

  • Try to simplify and decompose task and parts of code. After resolving the simplest cases, start optimization.

  • Use one approach for pointers in the arrays for all parts of your code

  • Use a "system" of variables naming, like advice before, it will help with debug.

  • Use debug! Don't spend time with print(). Use debugging tools in IDEs

  • Always ask yourself "what if" in each operation.

May the Force be with you.

Serge Gnezdilov /Finn/

#leetcode #algoritms LeetCode #python #arrays

To view or add a comment, sign in

Others also viewed

Explore topics