← 返回 walmartlabs 的题目列表Validate N×N Grid as Latin Square
类型:qbank
Given an N×N integer grid, return whether each row and each column is a permutation of 1..N. The grid is rectangular only if N equals the number of columns — non-square inputs fail immediately.
Requirements
Input: grid: int[][] with n rows and m columns.
Return true only when n == m, every value is in [1, n], and every row and every column contains each value exactly once.
Return false for non-square inputs, missing values, duplicates within a row or column, or out-of-range values.
Examples
grid = [[1,2,3], [2,3,1], [3,1,2]] → true
grid = [[0,2,3], [2,3,1], [3,1,2]] → false (0 is out of range)
grid = [[1,3], [2,1]] → false (2 missing in row 0)
Notes
Two passes over the grid suffice: collect per-row sets and per-column sets, comparing each against the expected {1..n} set. Time O(n²), space O(n).
Watch the order of checks: validate n == m and value range first to avoid index-out-of-range surprises on irregular inputs.
The classic LeetCode "Valid Sudoku" only enforces 1-9 with sub-boxes; this Walmart variant generalizes to any N and drops the box constraint, so the sub-grid index math does not apply.
A common Java pitfall is creating one shared HashSet and forgetting to clear it between rows / columns; allocate per row / per column or use boolean arrays indexed by value.
Preparation
Code both a HashSet version and a boolean[] version and compare runtime on n = 1000.
Add a short clarification phase to the round: "Is the grid guaranteed square? Are values guaranteed in [1, n]?" — the asker often plants invalid inputs that exercise these branches.
Practice walking through the algorithm with an early-exit on the first invalid row / column, since the round graded the candidate on running test cases including malformed inputs.