• + 0 comments

    Python implementation within time constraints. The idea is to get a linear list for a given circle and set the starting pointer to where it should be after rotating N times instead of rotating each circle N times.

    def rotate(matrix: list[list[int]], count: int):
        m = len(matrix)
        n = len(matrix[0])
    
        # given circle 
        for r in range(min(m, n) // 2):
            max_x = n - r - 1
            max_y = m - r - 1
            # flattening the circle
            circle = (
                # top
                [matrix[r][i] for i in range(r, max_x + 1)] +
                # right
                [matrix[y][max_x] for y in range(r + 1, max_y)] +
                # bottom
                [matrix[max_y][i] for i in range(max_x, r - 1, -1)] + 
                # left
                [matrix[y][r] for y in range(max_y - 1, r, -1)]
            )
            length = len(circle)
            pointer = count % length
            idx = pointer
            
            # top
            for i in range(r, max_x + 1):    
                matrix[r][i] = circle[idx]
                idx = idx + 1 if idx < length - 1 else 0
            
            # right
            for i in range(r + 1, max_y):            
                matrix[i][max_x] = circle[idx]
                idx = idx + 1 if idx < length - 1 else 0
            
            # bottom   
            for i in range(max_x + 1, r, -1):            
                matrix[max_y][i - 1] = circle[idx]
                idx = idx + 1 if idx < length - 1 else 0
            
            # left
            for i in range(max_y, r + 1, -1):            
                matrix[i - 1][r] = circle[idx]
                idx = idx + 1 if idx < length - 1 else 0
        
    
    def matrixRotation(matrix, r):    
        rotate(matrix, r)
    
        for row in matrix:
            print(*row)