Make diagonals 1 through coordinate (x,y)
Filed under Samsung
Free read 1 of 3Confirm if it means both the main diagonal (slope +1) and anti-diagonal (slope -1) passing through (x, y).
The question
Given a 2D matrix initialized with 0s and a target coordinate (x, y), update all elements lying on both diagonals passing through (x, y) to 1.
Constraints
- Matrix dimensions N x N where 1 <= N <= 500
- Coordinate (x, y) is within bounds: 0 <= x, y < N
Examples
- Input
- N = 3, x = 1, y = 1
- Output
- [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
- Why
- Both main and anti-diagonals passing through center (1,1) are set to 1.
Approach
Confirm if it means both the main diagonal (slope +1) and anti-diagonal (slope -1) passing through (x, y).
Iterate through every cell (i, j) in the matrix and check if i - j == x - y or i + j == x + y.
Loop through possible row indices and directly compute the corresponding column indices for both diagonals, setting them to 1 in O(N) time.
Matrix bounds when diagonals hit borders; ensuring indices do not go out of range.
Solution
O(N^2) time, O(N^2) space
def makeDiagonals1(n, x, y):
mat = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if i - j == x - y or i + j == x + y:
mat[i][j] = 1
return mat
Tips
- What they are testing: Test corner coordinates (0,0) and edge intersections to verify diagonal bounds checking.
- Common mistake: Iterating over the entire matrix instead of just calculating the diagonal indices mathematically.
Related Samsung questions
Collected from public candidate posts and coding forums. Updated Nov 2026.