algoadvance

Given a 2D integer matrix matrix, return a new 2D matrix such that for each cell (i, j) in the new matrix:

Note:

Clarifying Questions:

  1. What should be the size of the new matrix?
    • The new matrix should have the same dimensions as the input matrix.
  2. Should the original matrix be modified?
    • No, the original matrix should remain unchanged.
  3. How should the edges and corners be handled since they have fewer than 8 neighbors?
    • Assume cells out of the boundary are zero.

Strategy:

  1. Initialize a new matrix with the same dimensions as the input matrix.
  2. Iterate through each cell in the original matrix.
  3. Compute the sum of the 8 surrounding cells.
    • Use boundary checks to ensure cells out of bounds are treated as 0.
  4. Set the value of the corresponding cell in the new matrix based on whether the sum is odd or even.
  5. Return the modified matrix.

Time Complexity:

Let’s proceed with the code implementation.

Code:

def modify_matrix(matrix):
    if not matrix or not matrix[0]:
        return []
    
    rows, cols = len(matrix), len(matrix[0])
    new_matrix = [[0]*cols for _ in range(rows)]

    for i in range(rows):
        for j in range(cols):
            sum_neighbors = 0
            
            # Calculate the sum of 8 surrounding cells
            for x in (-1, 0, 1):
                for y in (-1, 0, 1):
                    if x == 0 and y == 0:
                        continue
                    ni, nj = i + x, j + y
                    if 0 <= ni < rows and 0 <= nj < cols:
                        sum_neighbors += matrix[ni][nj]
            
            # Set the value in new_matrix
            new_matrix[i][j] = 1 if sum_neighbors % 2 != 0 else 0
    
    return new_matrix

# Example Usage:
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(modify_matrix(matrix))

This code should handle the input matrix as specified and produce an output matrix where each cell is determined by the sum of its neighboring cells.

Try our interview co-pilot at AlgoAdvance.com