Problem Statement:
You are given two integers, n
and m
, representing the dimensions of an n × m
matrix. The task is to construct an n × m
matrix such that:
- Each element in the matrix is
1
. - The sum of the elements of the matrix is even.
If it’s not possible to satisfy these conditions, you should output -1
.
Solution Explanation:
The problem can be broken down into the following steps:
-
Understanding the Matrix Composition:
- The matrix is of dimensions
n × m
. - Each element in the matrix is
1
. - The sum of the elements in the matrix will be
n * m
since every element is1
.
- The matrix is of dimensions
-
Check for Evenness:
- For the sum of all elements in the matrix to be even, the product of
n
andm
must be even. This is because the sum of all1
s (which equalsn * m
) needs to be even. - Therefore, if
n * m
is even, it’s possible to create the matrix where the sum of all elements is even. Ifn * m
is odd, it’s impossible to make the sum even with all elements being1
, and hence the output should be-1
.
- For the sum of all elements in the matrix to be even, the product of
-
Constructing the Matrix:
- If
n * m
is even, construct the matrix by filling all positions with1
. - The matrix can then be printed row by row.
- If
Edge Cases:
- If either
n
orm
is1
, the sum of the matrix elements will ben * m
. Ifn * m
is odd (e.g., when bothn
andm
are odd), output-1
. - The smallest possible input (e.g.,
n = 1
,m = 1
) should be handled correctly.
Time Complexity:
The time complexity of this solution is O(n * m)
because it involves iterating through each element of the n × m
matrix once to print it.
Space Complexity:
The space complexity is O(1)
in terms of additional space, as the solution does not use any extra space that scales with input size.