Extract the Boundary of a Matrix

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.5
Write boundary_elements(grid) for a rectangular 2D list grid with at least one row and column. Return a flat list of all elements on the outer boundary (first row, last row, first column, last column) in clockwise order starting from the top-left corner, without repeating any corner element.

Examples

Example 1
Input
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output
[1, 2, 3, 6, 9, 8, 7, 4]
Explanation

Top row left-to-right, right column top-to-bottom (excluding corner already used), bottom row right-to-left, left column bottom-to-top.

Constraints

  • 1 <= rows, cols <= 200

Topics

ListsMatrixNested Lists

Companies

AmazonFlipkart

Hints

Hint 1

If there is only one row or one column, handle it as a special case to avoid duplicating corners.

Hint 2

Walk top row, then right column (skip first row), then bottom row reversed (skip last column), then left column reversed (skip first and last row).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.