Leetcode 3142. Check if Grid Satisfies Conditions
We are given a grid of size n x n
and our task is to determine if this grid satisfies the following conditions:
[1, n^2]
.n
?n x n
matrix.n
is reasonable, as typically given in competitive programming constraints.true
, otherwise false
.The strategy to solve this problem involves three main checks:
[1, n^2]
.import java.util.HashSet;
import java.util.Set;
public class GridChecker {
public boolean checkGrid(int[][] grid) {
int n = grid.length;
if (n == 0) return false; // Sanity check
Set<Integer> seen = new HashSet<>();
int expectedSum = 0;
// Calculate the sum of the first row to use as a reference
for (int i = 0; i < n; i++) {
expectedSum += grid[0][i];
}
// Validate all numbers in range and distinct, also check the sums of rows and columns
for (int i = 0; i < n; i++) {
int rowSum = 0;
int colSum = 0;
for (int j = 0; j < n; j++) {
int num = grid[i][j];
// Check if the number is in the valid range
if (num < 1 || num > n * n) {
return false;
}
// Check if the number is distinct
if (!seen.add(num)) {
return false;
}
rowSum += num;
colSum += grid[j][i];
}
// Check if the current row sum and column sum match the expected sum
if (rowSum != expectedSum || colSum != expectedSum) {
return false;
}
}
return true;
}
public static void main(String[] args) {
GridChecker checker = new GridChecker();
int[][] grid1 = {
{1, 2},
{3, 4}
};
int[][] grid2 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(checker.checkGrid(grid1)); // true
System.out.println(checker.checkGrid(grid2)); // false
}
}
Given n x n
grid, the overall time complexity is O(n^2)
.
This solution is efficient because each element is processed a constant number of times, making it well-suited for reasonably large n
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?