Run Time Error : Last executed input: [[7],[9],[6]]

• Below is my solution and got the Run Time Error saying that : Last executed input: [[7],[9],[6]].
But I've tested that in my local environment and got the answer [7, 9, 6].

``````vector<int> spiralOrder(vector<vector<int> > &matrix) {
int m = matrix.size();
int n = 0;
if(m != 0) {
n = matrix[0].size();
}

vector<int> retVector(m*n);
int currentIndex =0;

for(int i=0; 2*i < m; i++) {
//Top
for(int j=i; j <= n-1-i; j++) {
retVector[currentIndex++] = matrix[i][j];
}

//Right
for(int j=i+1; j<= m-1-i; j++) {
retVector[currentIndex++] = matrix[j][n-1-i];
}

//Bottom
for(int j=n-2-i; j>=i; j--) {
retVector[currentIndex++] = matrix[m-1-i][j];
}

//Left
for(int j=m-2-i; j>i; j--) {
retVector[currentIndex++] = matrix[j][i];
}
}

return retVector;
}
``````

Any suggestions?

• You are inserting more elements into the vector than the reserved capacity.

For this test case:
The Top loop covers all the elements. currentIndex = 3, by the end of this loop.
It doesn't enter the Right loop.
The problem is in the Bottom loop, 1st row is again getting inserted.
retVector[3++] = matrix[0][1], trying to insert 4th element, where it can hold only 3 elements.

Similarly you need to fix the left loop, for n=1.
I haven't checked for other test cases.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.