-2

You can read description of the problem at: https://leetcode.com/problems/spiral-matrix I was trying to solve this problem and I came up with the following code. But it fails due to IndexError: pop from empty list error. Take a look at the code:

    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        answer = []
        while matrix:
            answer.append(matrix.pop(0))
            for i in range(len(matrix)):
                answer.append(matrix[i].pop())
            #print(matrix)
            answer.append(matrix.pop(-1))
            for i in range(len(matrix))[::-1]:
                answer.append(matrix[i].pop(0))
        return answer

The program deletes the first row of the matrix, then deletes last elements of all rows, then it is supposed to delete the last row but this is where the error arises. To understand why this happens I tried to output matrix before this step (imagine that #print(matrix) is now uncommented) So in the testcase where matrix = [[1,2,3],[4,5,6],[7,8,9]] the output is [[4, 5], [7, 8]] [] These last 2 brackets seem to be causing the mistake. Where do they come from and how do I get rid of them?

  • 1
    Hint: where the code says `while matrix:`, how many times do you think that condition will be checked **per loop**? Now, how many times will `matrix.pop` be attempted per loop? Do you see how this causes a problem? – Karl Knechtel Jan 16 '23 at 11:16

1 Answers1

0

well you need to check the element/row which you are removing is present there or not. when removing a row use extend and when removing element use append method with answer.

when in 3 spiral ie (1. right -> left, 2. top -> bottom 3. right -> left, 4 bottom -> top). you need to reverse the element of removed sublist.

Below is updated code which worked in leetcode

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
            answer = []
            while matrix:
                if matrix:
                    answer.extend(matrix.pop(0))
    
                for i in range(len(matrix)):
                    if matrix[i]:
                        answer.append(matrix[i].pop())
                #print(matrix)
                if matrix:
                    answer.extend(matrix.pop(-1)[::-1])
                for i in range(len(matrix))[::-1]:
                    if matrix[i]:
                        answer.append(matrix[i].pop(0))
            return answer
sahasrara62
  • 10,069
  • 3
  • 29
  • 44