Matrix Spiral Copy(Java Solution)

Big_Dream_Coder
2 min readJun 24, 2022

A Question on Pramp platform

There are two ways of solving this question. One is iterative way, the other is recursive way. When I doing mocking interview on Pramp, the first solution that I come up with is to solve it in iterative way like the code below.

static int[] spiralCopy(int[][] inputMatrix) {
// your code goes here
int m = inputMatrix.length;
int n = inputMatrix[0].length;
int[] ans = new int[m * n];
int index = 0;

int leftBound = 0, rightBound = n - 1;
int upperBound = 0, lowerBound = m - 1;
while(index < m * n){
if(upperBound <= lowerBound){
for(int i = leftBound; i <= rightBound; i++){
ans[index++] = inputMatrix[upperBound][i];
}
upperBound++;
}
if(leftBound <= rightBound){
for(int i = upperBound; i <= lowerBound; i++){
ans[index++] = inputMatrix[i][rightBound];
}
rightBound--;
}
if(upperBound <= lowerBound){
for(int i = rightBound; i >= leftBound; i--){
ans[index++] = inputMatrix[lowerBound][i];
}
lowerBound--;
}
if(leftBound <= rightBound){
for(int i = lowerBound; i >= upperBound; i--){
ans[index++] = inputMatrix[i][leftBound];
}
leftBound++;
}
}
return ans;
}

After mocking interview, I tried to solve it with recursive function. Then, here comes the code below.

  static int index = 0;  static int[] spiralCopy(int[][] inputMatrix) {
// your code goes here
int m = inputMatrix.length;
int n = inputMatrix[0].length;
int[] ans = new int[m * n];
index = 0;
spiralOut(inputMatrix, ans, 0, m - 1, 0, n - 1);
return ans;
}
static void spiralOut(int[][] inputMatrix, int[] ans, int upperbound, int lowerbound, int leftbound, int rightbound){
if(upperbound > lowerbound || leftbound > rightbound) return;
for(int i = leftbound; i <= rightbound; i++){
ans[index++] = inputMatrix[upperbound][i];
}
for(int i = upperbound + 1; i <= lowerbound; i++){
ans[index++] = inputMatrix[i][rightbound];
}
if(upperbound == lowerbound || leftbound == rightbound) return;
for(int i = rightbound - 1; i >= leftbound; i--){
ans[index++] = inputMatrix[lowerbound][i];
}
for(int i = lowerbound - 1; i >= upperbound + 1; i--){
ans[index++] = inputMatrix[i][leftbound];
}
spiralOut(inputMatrix, ans, upperbound + 1, lowerbound - 1, leftbound + 1, rightbound - 1);
}

Both solutions’ time complexity is O(m * n) and the space complexity is O(m * n).

--

--