Amazon Interview Question for Software Engineer / Developers


Country: India
Interview Type: Written Test




Comment hidden because of low score. Click to expand.
8
of 8 vote

private static int[][] rotateMatrixBy90Degree(int[][] matrix, int n) {
		for (int layer = 0; layer < n / 2; layer++) {
			int first = layer;
			int last = n - 1 - layer;
			for (int i = first; i < last; i++) {
				int offset = i - first;
				int top = matrix[first][i];
				matrix[first][i] = matrix[last - offset][first];
				matrix[last - offset][first] = matrix[last][last - offset];
				matrix[last - offset][last] = matrix[i][last];
				matrix[i][last] = top;
			}
		}
		System.out.println("Matrix After Rotating 90 degree:-");
		printMatrix(matrix, n);
		return matrix;

	}

- Vir Pratap Uttam May 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
4
of 4 vote

suck it fellows

import sys
data = sys.stdin.read().strip().split('\n')

mat_size = int(data[0])
rot = data[len(data) -1]
a = [[int(y) for y in data[x].split()] for x in range(1, mat_size+1)]
c = None
d = lambda a, b: zip(*a)[::-1] if b == '90' else zip(*a[::-1])
c = d(a, rot)
print '\n'.join(map(str, map(lambda i: ' '.join(map(str, c[i])), range(mat_size))))

- suckit March 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

HERE IT IS ..FULLY TESTED WITH OUTPUT..

If U WANT TO rotate pi/2 in counter-clockwise

1) transpose the array

2) reverse the elements on column order

never test the code! any suggestion would be appreciated!

import java.io.*;
public class Rotate{

public static void reverseElementsRowWise(int[][] matrix) {
int n = matrix.length;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n / 2; ++j) {
int temp = matrix[i][n - j - 1];
matrix[i][n - j - 1] = matrix[i][j];
matrix[i][j] = temp;
}
}
}

public static void transpose(int[][] matrix) {
int n = matrix.length;
for(int i = 0; i < n; ++i) {
for(int j = i + 1; j < n; ++j) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}

public static void rotate90(int[][] matrix) {
transpose(matrix);
reverseElementsRowWise(matrix);
}

public static void print(int[][] matrix) {
int n = matrix.length;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
System.out.print(matrix[i][j]);
System.out.print(' ');
}
System.out.println();
}
}

public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
System.out.println("before rotate to 90");
print(matrix);
rotate90(matrix);
System.out.println("after rotate to 90");
print(matrix);
}
}


output:

before rotate to 90
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
after rotate to 90
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4

- subbu September 05, 2013 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

public class RotateMatrix {
    final int ROW = 5;
    final int COL = 5;
	public static void main(String[] args) {
		int mat[][] = {{2,1,5,3,4},{5,8,6,4,4},{9,12,6,9,4},{8,7,6,5,2},{1,2,3,4,5}};
		RotateMatrix rm = new RotateMatrix();
		System.out.println("Original Matrix:");
		rm.displayMat(mat);
		//Get transpose of matrix
        int temp;
		for(int i=0, j=0; i<rm.ROW; i++){
			j=i;
			for(; j<rm.COL; j++){
				if(i!=j){
					temp = mat[i][j];
					mat[i][j] = mat[j][i];
					mat[j][i] = temp;					
				}				
			}
		}
		System.out.println("Matrix after transpose:");
		rm.displayMat(mat);
		int c = 0;
		while(c<rm.COL/2){
			for(int i=0; i<rm.ROW; i++){
				temp = mat[i][c];
				mat[i][c] = mat[i][rm.COL-c-1];
				mat[i][rm.COL-c-1] = temp;
			}
			c++;
		}
		System.out.println("Matrix after rotation:");
		rm.displayMat(mat);
	}
	void displayMat(int mat[][]){

		for(int i=0; i<ROW; i++){
			for(int j=0; j<COL; j++){
				System.out.print(mat[i][j]+" ");
			}
			System.out.print("\n");
		}
		System.out.print("\n");
	}
}

- Razz March 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

nicely done

- lb March 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

void rotate (int** matrix, int n)
{
for(int layer=0;layer< n/2;layer++)
{
int first=layer;
int last=n-1-layer;
for(int i=first;i<last;i++)
{
int offset=i-first;
int top=matrix[first][i];
matrix[first][i]=matrix[last-offset][first];
matrix[last-offset][first]=matrix[last][last-offset];
matrix[last][last-offset]=matrix[i][last];
matrix[i][last]=top;
}
}
}


start from the layer 0 to layer n/2, and rotate each element in the each layer.

- princess March 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

So you started reading cracking the coding interview :P

- Nitin Gupta March 05, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
	int num_row, num_column;
	string tmp;
	cout << "how many rows?" << endl;
	getline(cin, tmp);
	num_row = atoi(tmp.c_str());
	cout << "how many column?" << endl;
	getline(cin, tmp);
	num_column = atoi(tmp.c_str());

	string matrix[num_row][num_column];

	for(int x = 0; x < num_row; x++) {
		string oneline;
		cout << "please input the " << x+1 <<  " row. Using spaces to seperate each number: ";
		getline(cin, oneline);
		cout << "oneline: " << oneline << endl;
		istringstream iss(oneline);
		int y = 0;
		do {
			string sub;
			iss >> sub;
			if (sub.compare("") != 0 )
			{
				matrix[x][y] = sub;
				cout << "matrix[" << x << "][" << y << "]: " << sub << endl;
			}
			y++;
		} while (iss);
	}

	cout << "old matrix:" << endl;
	for (int b = 0; b < num_row; ++b)
	{
		for (int c = 0; c < num_column; ++c)
		{
			cout << matrix[b][c] << " ";
		}
		cout << endl;
	}

	string new_matrix[num_column][num_row];

	for (int i = 0; i < num_row; ++i)
	{
		for (int a = 0; a < num_column; ++a)
		{
			new_matrix[a][num_row - i - 1] = matrix[i][a];
		}
	}

	cout << "after rotation, the matrix now is:" << endl;
	for (int b = 0; b < num_column; ++b)
	{
		for (int c = 0; c < num_row; ++c)
		{
			cout << new_matrix[b][c] << " ";
		}
		cout << endl;
	}
	return 0;
}

- nUO March 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <math.h>
#define ROW 5
#define COL 5

int main(int argc, char* argv[])
{
	int mat[ROW][COL] = {	{1, 2, 3, 4, 5},
							{6, 7, 8, 9, 10},
							{11, 12, 13, 14, 15},
							{16, 17, 18, 19, 20},
							{21, 22, 23, 24, 25}
						};

	//Print Matrix
	for(int i = 0; i < ROW; i++)
	{
		for (int j = 0; j < COL; j++)
			printf("%2d ", mat[i][j]);
		printf("\n");
	}
	printf("\n");
	printf("\n");

	int C = COL - 1, R = ROW - 1, temp = 0;

	for ( int i = 0; i < R; i++ )
	{
		C = R;
		for(int j = i; j < COL - 1 - i; j++)
		{
			temp = mat[i][j];
			mat[i][j] = mat[C][i];
			mat[C][i] = mat[R][C];
			mat[R][C] = mat[j][R];
			mat[j][R] = temp;
			--C;
		}
		--R;
	}

	//Print Matrix
	for(int i = 0; i < ROW; i++)
	{
		for (int j = 0; j < COL; j++)
			printf("%2d ", mat[i][j]);
		printf("\n");
	}
	return 0;
}

- Anndy March 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

can we also do like that


#include<stdio.h>
#include<conio.h>
#define ROW 3
#define COL 4
int main()
{
int i,j;
int a[ROW][COL]={ {1, 2, 3, 0},
{4, 5, 6, 0},
{7, 8, 9, 0}};

printf("The given matrix is as follows:\n\n");

for(i=0;i<ROW;i++){
for(j=0;j<COL;j++)
printf("%d\t",a[i][j]);
printf("\n\n");
}

printf("After rotating it to 90 degree:\n\n");

for(i=0;i<COL;i++){
for(j=ROW -1;j>=0;j--)
printf("%d\t",a[j][i]);
printf("\n\n");
}




getch();
return 0;
}

- swapnil March 05, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

that I guess will be hack....not a solution to the problem.

- Anndy March 05, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def rotate_matrix(m):
    r=[]
    for i in range(len(m)):
        lx=len(m[i])
        y=[]
        for j in range(lx):
            try:
                y.append(m[lx-j-1][i])
            except:
                pass
        r.append(y)
    for l in r:
        print l

- Anonymous March 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

What if it's not a square matrix?

- aimjwizards March 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about just playing with the loops!

- Krish March 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void rotate(int a[3][3])
{
	int b[3][3],i,j;

	for(i=0;i<3;i++)
		for(j=0;j<3;j++)
			b[j][2-i]=a[i][j];
	for(i=0;i<3;i++)
		for(j=0;j<3;j++)
			a[i][j]=b[i][j];


}

- rajivnewid March 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

suck it fellows

import sys
data = sys.stdin.read().strip().split('\n')

mat_size = int(data[0])
rot = data[len(data) -1]
a = [[int(y) for y in data[x].split()] for x in range(1, mat_size+1)]
c = None
d = lambda a, b: zip(*a)[::-1] if b == '90' else zip(*a[::-1])
c = d(a, rot)
print '\n'.join(map(str, map(lambda i: ' '.join(map(str, c[i])), range(mat_size))))

- suckit March 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assuming the matrix is n*n

void rotate(int *mat[], int n)
{
    int layer = 0, first = 0, last = 0, temp = 0, i = 0;

    for (layer = 0; layer < n/2; layer++)
    {
        first = layer;
        last = n - 1 - first;

        for (i = first; i < last; i++)
        {
            temp = mat[first][i];
            mat[first][i] = mat[last - i][first];
            mat[last - i][first] = mat[last][last - i];
            mat[last][last - i] = mat[i][last];
            mat[i][last] = temp;
        }
    }
}

- Ashish19121 March 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void rotate90(int[][] value){
int pos;
int[][] result = new int[value[0].length][value.length];
for(int i = 0 ; i < value.length; i++){
for(int j = 0 ; j < value[0].length ; j++){
pos = value.length-1-i;
result[j][pos] = value[i][j];
}
}

}

- Sudharshan March 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void rotate90(int[][] value){
		int pos;
		int[][] result = new int[value[0].length][value.length];
		for(int i = 0 ; i < value.length;  i++){
			for(int j = 0 ; j < value[0].length ; j++){
				pos = value.length-1-i;
				result[j][pos] = value[i][j];
			}
		}
		
	}

- sudharshan March 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void rotate90()
	{
		int[][] rotatedMatrix = new int[size][size];
		for(int i=0; i<size;i++)
		{
			for(int j=0;j<size;j++)
			{
				rotatedMatrix[i][j]=matrix[size-1-j][i];
			}
		}
		matrix=rotatedMatrix;
	}

- sandhya -- March 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Matrix {

static int[][] getMcrossN(int m, int n){
int[][] a = new int[m][n];
int cnt = 1;
for(int i=0; i<m; i++){
for(int j=0;j<n; j++){
System.out.format("%4d",a[i][j]=cnt++);
}
System.out.println();
}
System.out.println("\n\n");
return a;
}

static int[][] rotateMatrix(int[][] x){
int[][] m = new int[x[0].length][x.length];
for(int i=0; i<x[0].length; i++){
for(int j=0; j<x.length; j++){
// System.out.format("%4d",m[i][j]=x[j][x[0].length-1-i]); //rotate by 90 degree anticlockwise.
System.out.format("%4d",m[i][j]=x[x.length-1-j][i]); //rotate by 90 degree clockwise.
}
System.out.println();
}
return m;
}
/**
* @param args
*/
public static void main(String[] args) {
rotateMatrix(getMcrossN(3, 4));
}
}

- zoro's hub July 12, 2013 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More