Similar Problems
Similar Problems not available
Build A Matrix With Conditions - Leetcode Solution
Companies:
LeetCode: Build A Matrix With Conditions Leetcode Solution
Difficulty: Hard
Problem statement:
Given two integers n and m, you need to build an n x m matrix with certain conditions. The matrix should have all numbers in the range of 1 to n*m, and the following conditions should be satisfied:
- The ith row and jth column of the matrix should contain the number (i+j-1).
- All the numbers in the matrix should be distinct.
Return the matrix if it is possible to construct such a matrix, otherwise, return an empty array.
Solution:
To solve this problem, we need to first check if it is possible to construct a matrix that satisfies the given conditions. If the number of rows times the number of columns is greater than the total number of distinct numbers from 1 to nm, we cannot construct such a matrix. Once we know it is possible to construct the matrix, we can create a 2D array of size n x m and fill it with the numbers from 1 to nm based on the given conditions.
Following is the detailed solution in Python:
class Solution:
def constructMatrix(self, n: int, m: int) -> List[List[int]]:
# check if it is possible to construct the matrix
if n * m < 1 or n * m > 10000:
return []
if n == 1:
return [[i] for i in range(1, m+1)]
if m == 1:
return [[i] for i in range(1, n+1)]
if n * m != len(set(range(1, n*m+1))):
return []
# create the matrix and fill it with numbers based on the conditions
matrix = [[0 for j in range(m)] for i in range(n)]
for i in range(n):
for j in range(m):
matrix[i][j] = i + j + 1
for i in range(n):
for j in range(m):
if (i + j) % 2 != 0:
matrix[i][j] = (i+1) * m - j
return matrix
In this solution, we have used the following approach:
- We first check if it is possible to construct the matrix based on the given values of n and m. We return an empty array if it is not possible.
- We then create an empty matrix of size n x m using the list comprehension method in Python.
- We fill the matrix with numbers based on the given conditions.
- We check if any numbers are repeated in the matrix. If any numbers are repeated, we return an empty array.
- Finally, we return the constructed matrix.
Build A Matrix With Conditions Solution Code
1