Zoho Interview Question
SDE1sCountry: United States
Interview Type: Written Test
public void rotateMatrix(int matrix [] [], int size){//size is the size of the matrix MxM
int [][] rotatedMatrix = new int [size][size];
for(int colIndex = 0; colIndex<size; colIndex++){
for(int rowIndex=0; rowIndex<size; rowIndex++){
rotatedMatrix[colIndex][rowIndex] = matrix [(size-1)-rowIndex][colIndex];// not sure why i did it this way.
}
}
for(int x=0; x<size; x++){
for(int y=0; y<size; y++){
System.out.println(rotatedMatrix[x][y]);
}
}
}
public int[][] rotate(int[][] m)
{
if(m==null||m.length==m[0].length)
{
return null;
}
for(int layer=0;layer<m.length/2;layer++)
{
int minRow=layer;
int minCol=minRow;
int maxRow=m.length-layer-1;
int maxCol=maxRow;
if (minRow==maxRow)
{
break;
}
int tmp=m[minRow][minCol];
for(int i=minRow+1;i<=maxRow;i++)
{
m[i-1][minCol]=m[i][minCol];
}
for(int i=minCol+1;i<=maxCol;i++)
{
m[maxRow][i-1]=m[maxRow][i];
}
for(int i=maxRow-1;i>=minRow;i--)
{
m[i+1][maxCol]=m[i][maxCol];
}
for(int i=maxCol-1;i>minCol;i--)
{
m[minRow][i+1]=m[minRow][i];
}
m[minRow][minCol+1]=tmp;
}
return m;
}
//Time Complexity: O(n^2) where n is the number of rows/columns in the input matrix.
#include <stdio.h>
#define MAX_ARRAY_SIZE 10
void rotateMatrix(int size, int(*arr)[MAX_ARRAY_SIZE], int(*arr_to)[MAX_ARRAY_SIZE]);
void getNextCoordination(int size_from, int size_to, int x, int y, int *x_to, int *y_to);
void printArray(int size, int(*arr)[MAX_ARRAY_SIZE]);
int main()
{
int arr[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE] = { 0, };
int arr_to[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE] = { 0, };
for (int i = 3; i <= 5; i++)
{
int num = 1;
for (int k = 0; k < i; k++)
for (int l = 0; l < i;l++)
arr[k][l] = num++;
rotateMatrix(i, arr, arr_to);
printArray(i, arr);
printArray(i, arr_to);
}
return 0;
}
void rotateMatrix(int size, int(*arr)[MAX_ARRAY_SIZE], int(*arr_to)[MAX_ARRAY_SIZE])
{
int size_from = 0;
int size_to = size - 1;
int x, y, x_to, y_to;
while (size_from <= size_to)
{
x = size_from;
y = size_from;
if (size_from == size_to)
{
arr_to[x][y] = arr[x][y];
}
else
{
for (int i = 1; i <= (((size_to - size_from + 1) * 2) + (((size_to - size_from + 1) - 2) * 2)); i++)
{
getNextCoordination(size_from, size_to, x, y, &x_to, &y_to);
arr_to[x_to][y_to] = arr[x][y];
x = x_to;
y = y_to;
}
}
size_from++;
size_to--;
}
}
void getNextCoordination(int size_from, int size_to, int x, int y, int *x_to, int *y_to)
{
if (x == size_from)
{
if (y < size_to)
{
*x_to = x;
*y_to = y + 1;
}
else
{
*x_to = x + 1;
*y_to = y;
}
}
else if (x > size_from && x < size_to)
{
if (y == size_from)
{
*x_to = x - 1;
*y_to = y;
}
else if (y == size_to)
{
*x_to = x + 1;
*y_to = y;
}
}
else if (x == size_to)
{
if (y > size_from)
{
*x_to = x;
*y_to = y - 1;
}
else
{
*x_to = x - 1;
*y_to = y;
}
}
}
void printArray(int size, int(*arr)[MAX_ARRAY_SIZE])
{
printf("---------------------\n");
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
printf("%2d ", arr[i][j]);
}
printf("\n");
}
}
- Raj June 23, 2016