# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
# Basic Approach (Time: O(m*n); Space: O(1))
def spiral_matrix(mat):
    res = []
    m = len(mat[0])
    n = len(mat)
    p = m
    q = n
    x = w = 0
    y = m - 1
    z = n - 1
    while True:
        # Right-direction
        i = m - p
        while i < p:
            res.append(mat[x][i])
            i += 1
        x += 1
        p -= 1
        if len(res) == n * m:
            break
        # Down-direction
        i = n - q + 1
        while i < q:
            res.append(mat[i][y])
            i += 1
        y -= 1
        q -= 1
        if len(res) == n * m:
            break
        # Left-direction
        i = p - 1
        while i >= m - p - 1:
            res.append(mat[z][i])
            i -= 1
        z -= 1
        if len(res) == n * m:
            break
        # Up-direction
        i = q - 1
        while i >= n - q:
            res.append(mat[i][w])
            i -= 1
        w += 1
        if len(res) == n * m:
            break
    return res

print(spiral_matrix([[1,2,11,12], [4, 5, 6, 7]]))

# +
# Inputs:
# - [[1,2,3],[4,5,6],[7,8,9]]
# - [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

StarcoderdataJupyterScriptsDedupFiltered