Problem 288955 · medium · Phase 02 Linear Data Structures

Trim to the Bounding Box

2d-lists · cropping · min-max

Given a grid of integers grid, return a new grid that is the smallest rectangular sub-grid containing every non-zero cell (rows and columns on the outside that are entirely zero are removed). If the grid has no non-zero cell, return [].

Examples

Input:  grid = [[0, 0, 0, 0],
                [0, 1, 0, 0],
                [0, 0, 2, 0],
                [0, 0, 0, 0]]
Output: [[1, 0],
         [0, 2]]

Input:  grid = [[0, 0],
                [0, 0]]
Output: []

Input:  grid = [[0, 5, 0]]
Output: [[5]]

Constraints

  • 1 <= rows, cols <= 100
  • The input grid must not be modified.

Goals

  • Find the smallest rectangle that contains every non-zero cell
  • Extract a sub-grid using slices
Starting Python…