Validate that each row and column of a square matrix is a permutation of 1 to n

Quick Overview

Return whether a square integer matrix has every row and every column holding all of the numbers from 1 to n. It tests building the expected set of values, scanning columns as carefully as rows, and stating the time and space cost of a grid check.

Validate that each row and column of a square matrix is a permutation of 1 to n

Company: Instacart

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

An `n x n` matrix is **valid** if every row and every column contains all the integers from `1` to `n` (inclusive). Given an `n x n` integer matrix `matrix`, return `True` if the matrix is valid. Otherwise, return `False`. ### Function Signature ```python def check_valid(matrix: list[list[int]]) -> bool: ... ``` ### Rules - `matrix` is a list of `n` rows, and each row is a list of `n` integers. - Return a Python `bool`. ### Constraints - `n == len(matrix) == len(matrix[i])` - `1 <= n <= 100` - `1 <= matrix[i][j] <= n` ### Examples ```text Input: matrix = [[1, 2, 3], [3, 1, 2], [2, 3, 1]] Output: True ``` Every row contains `{1, 2, 3}` and every column contains `{1, 2, 3}`, so the matrix is valid. ```text Input: matrix = [[1, 1, 1], [1, 2, 3], [1, 2, 3]] Output: False ``` The first row contains only 1s, which is not `{1, 2, 3}`. The first column is `{1, 1, 1}`, also invalid.

Overview: Return whether a square integer matrix has every row and every column holding all of the numbers from 1 to n. It tests building the expected set of values, scanning columns as carefully as rows, and stating the time and space cost of a grid check.

Instacart logo
Instacart
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).

Given an n x n integer matrix matrix, return True if the matrix is valid. Otherwise, return False.

Function Signature

def check_valid(matrix: list[list[int]]) -> bool:
    ...

Rules

  • matrix is a list of n rows, and each row is a list of n integers.
  • Return a Python bool .

Constraints

  • n == len(matrix) == len(matrix[i])
  • 1 <= n <= 100
  • 1 <= matrix[i][j] <= n

Examples

Input: matrix = [[1, 2, 3], [3, 1, 2], [2, 3, 1]]
Output: True

Every row contains {1, 2, 3} and every column contains {1, 2, 3}, so the matrix is valid.

Input: matrix = [[1, 1, 1], [1, 2, 3], [1, 2, 3]]
Output: False

The first row contains only 1s, which is not {1, 2, 3}. The first column is {1, 1, 1}, also invalid.