Skip to content

Instantly share code, notes, and snippets.

@farleylai
Last active September 2, 2015 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farleylai/64a8c8b84ac5dca04221 to your computer and use it in GitHub Desktop.
Save farleylai/64a8c8b84ac5dca04221 to your computer and use it in GitHub Desktop.
Sample Interview Question: Print the spiral given a 2D array
void printSpiral(A, int r, int c, int rows, int cols) {
if(A == null || rows < 1 || cols < 1) {
System.out.println();
return;
}
if(rows == 1) {
for(int i = 0; i < cols; i++)
print(A[r][c+cols-1-i] + " ");
} else if(cols == 1) {
for(int i = 0; i < rows; i++)
print(A[r+rows-1-i][c] + " ");
} else {
// print bounds
for(int i = 0; i < rows-1; i++)
print(A[r+rows-1-i][c+cols-1] + " ");
for(int i = 0; i < cols-1; i++)
print(A[r][c+cols-1-i] + " ");
for(int i = 0; i < rows-1; i++)
print(A[r+i][c] + " ");
for(int i = 0; i < cols-1; i++)
print(A[r+rows-1][c+i] + " ");
}
// recursive
printSpiral(A, r+1, c+1, rows-2, cols-2);
}
def A = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
];
def B = [
[1, 2, 3],
[4, 5, 6],
];
def C = [[1]];
def D = [
[],
];
def E = [
[1],
[2],
[3],
];
printSpiral(A, 0, 0, A.size, A[0].size);
printSpiral(B, 0, 0, B.size, B[0].size);
printSpiral(C, 0, 0, C.size, C[0].size);
printSpiral(D, 0, 0, D.size, D[0].size);
printSpiral(E, 0, 0, E.size, E[0].size);
printSpiral(null, -1, -1, 0, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment