Skip to main content

Matrix Rotation - Medium


Problem - Write an algorithm capable of rotating a matrix, in-place without any auxiliary storage.

I don't have an elaborate thought process to develop this algorithm. It's a few rules you ought to remember to implement rotations in the matrix.

To implement these rules, you need some helper functions which are quite simple really. You need to be able to transpose a matrix, reverse a row, reverse a column. That's it. The rest is just a combination of these 3 functions.


def transpose(X):
return map(list,zip(*X))
def reverse_rows(X):
return map(lambda x:list(reversed(x)),X)
def reverse_cols(X):
return list(reversed(X))
Python is awesome, isn't it?
Note : These functions create copies of the matrix, we can design algorithms that modify the original matrix with ease for square matrices. For non-square matrices, we have to create new matrices.

Okay, let's get to the rotations. So we need to perform three kinds of rotations. 90,180,270.

1) Rotation by 90/-270  degrees

  1. Transpose the Matrix
  2. Reverse each row

2) Rotation by 180/-180 degrees

There are two methods:

First Method, is clearly obvious, perform 90 degree rotation twice.
Second Method contains two steps, both these operations can be done in any order,

  1. Reverse Each Row
  2. Reverse Each Column 

3) Rotation by 270/-90 degrees

  1. Transpose the matrix
  2. Reverse each column


def rotate_right_90(X):
return reverse_rows(transpose(X))
def rotate_right_180(X):
return reverse_rows(reverse_cols(X))
def rotate_left_90(X):
return reverse_cols(transpose(X))
print "Original Matrix"
pprint.pprint(mtx)
print "90/-270 degree rotation"
pprint.pprint(rotate_right_90(mtx))
print "180/-180 degree rotation"
pprint.pprint(rotate_right_180(mtx))
print "270/-90 degree rotation"
pprint.pprint(rotate_left_90(mtx))

You can find the entire source code here.

Comments

Popular posts from this blog

Find Increasing Triplet Subsequence - Medium

Problem - Given an integer array A[1..n], find an instance of i,j,k where 0 < i < j < k <= n and A[i] < A[j] < A[k]. Let's start with the obvious solution, bruteforce every three element combination until we find a solution. Let's try to reduce this by searching left and right for each element, we search left for an element smaller than the current one, towards the right an element greater than the current one. When we find an element that has both such elements, we found the solution. The complexity of this solution is O(n^2). To reduce this even further, One can simply apply the longest increasing subsequence algorithm and break when we get an LIS of length 3. But the best algorithm that can find an LIS is O(nlogn) with O( n ) space . An O(nlogn) algorithm seems like an overkill! Can this be done in linear time? The Algorithm: We iterate over the array and keep track of two things. The minimum value iterated over (min) The minimum increa...

Dijkstra's algorithm - Part 1 - Tutorial

This will be a 3 Part series of posts where I will be implementing the Dijkstra's Shortest Path algorithm in Python. The three parts will be 1) Representing the Graph 2) Priority Queue 3) The Algorithm To represent a graph we'll be using an  Adjacency List . Another alternative is using an Adjacency Matrix, but for a sparse graph an Adjacency List is more efficient. Adjacency List An Adjacency List is usually represented as a HashTable (or an Array) where an entry at `u` contains a Linked List. The Linked List contains `v` and optionally another parameter `w`. Here `u` and `v` are node(or vertex) labels and `w` is the weight of the edge. By Traversing the linked list we obtain the immediate neighbours of `u`. Visually, it looks like this. For implementing this in Python, we'll be using the dict()  for the main HashTable. For the Linked List we can use a list of 2 sized tuples (v,w).  Sidenote: Instead of a list of tuples, you can use a dict(), ...

Find the Quadruplets - Hard

Problem - Given 4 arrays A,B,C,D. Find out if there exists an instance where A[i] + B[j] + C[k] + D[l] = 0 Like the Find the Triple problem, we're going to develop 4 algorithms to solve this. Starting with the naive O(n^4) solution. Then we proceed to eliminate the inner-most loop with a Binary Search, reducing the complexity to O(n^3 logn) Now, we replace the last 2 loops with the left-right traversal we did in the previous 3 posts. Now the complexity is O(n^3). Finally, we reduce the complexity to O(n^2 logn) at the cost of O(n^2) Space Complexity. We store every combination of A[i] + B[j] and store it in AB[]. Similarly we make CD[] out of C[i] + D[j]. So, AB = A x B CD = C x D We then sort AB and CD (which costs O(n^2 log(n^2)) ~ O(n^2 logn) ) and then run a left-right linear Algorithm on AB and CD. (Note : Their size is of the order O(n^2)) So the overall complexity is due to sorting the large array of size n^2. which is O(n^2 logn).