progress

~/problems / Math & matrices

Walk the outer ring of a grid

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write outer_ring(grid: list[list[int]]) -> list[int] that returns the values on the edge of an m x n grid, clockwise, starting at the top-left corner: the top row left to right, down the right column, the bottom row right to left, then up the left column. Each edge cell appears exactly once, corners included.

outer_ring([[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]])            # [1, 2, 3, 6, 9, 8, 7, 4]
outer_ring([[1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12]])      # [1, 2, 3, 4, 8, 12, 11, 10, 9, 5]
outer_ring([[1, 2, 3]])            # [1, 2, 3]
outer_ring([[1], [2], [3]])        # [1, 2, 3]

Constraints: 1 <= m, n <= 100. Don't change grid.

Show hint

write the four sides as four loops. The bottom row only exists if m > 1, and the left column only if n > 1.

Topic: Math and matrices. Digit-by-digit arithmetic, matrix rotation and in-place tricks.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc