Rotate Image - Leetcode 48 - Arrays & Strings (Python)

preview_player
Показать описание


Please check my playlists for free DSA problem solutions:

My Favorite Courses:

Data Structures & Algorithms:

Python:

Web Dev / Full Stack:

Cloud Development:

Game Development:

SQL & Data Science:

Machine Learning & AI:
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

I love this series. Helps in understanding DSA a bit optimized way.

Kainum
Автор

Step 1 take transpose
Step 2 reverse row

jyotirmaysingh
Автор

When transposing the inner loop (i+1, n) definitely takes some extra thought. Wouldn't have been able to come up with that in an interview setting.

brandonblackwell
Автор

To conceptualize this, I tried flipping my notebook without rotating it. In every case this worked.

teostorm
Автор

Also, from the transposed matrix mT:
>>>list(map(operator.methodcaller('reverse'), mT))
does it inplace.

DrDeuteron
Автор

Without knowing this, what I found out is that you can rotate elements by "levels". Imagine the matrix as an onion, the first level would be the outermost layer consisting of the first and last row, and first and last column. So after rotating every element in the first level, you are left with an inner matrix of size N-1. So all you need to do is repeat the same process N // 2 times. N being the matrix' size.

Here's the code:
```
level = 1
N = len(matrix)
while level <= N // 2:
for i in range(level - 1, N - level):

tmp = matrix[level-1][i]
matrix[level-1][i] = matrix[-i-1][level-1]
matrix[-i-1][level-1] = matrix[-level][-i-1]
matrix[-level][-i-1] = matrix[i][-level]
matrix[i][-level] = tmp
level += 1
return matrix
```

I took advantage of python's negative indexing. The range keeps getting smaller until you reach the center of the matrix :)

ayrtoncoelho
Автор

What is the intuition behind this approach ? If not intuition, is it just by observation ?

darkhorse
Автор

couldn't we also do matrix[i].reverse() in the second loop?

thatbomb
Автор

In transpose part why the loop for J runs from (i+1 to n) instead of ( only n)

bibekkarki
Автор

matrix = list(map(list, map(reversed, zip(*matrix))))

DrDeuteron
Автор

Is this considered in-place modification -
for idx, lst in enumerate(map(reversed, zip(*matrix))):
matrix[idx] = list(lst)

JoeTan-nqfq
Автор

I feel like vertical reflection would make more sense haha.

teostorm
Автор

any tips on how to learn algorithms and data structures?

mauricemurillo