algoadvance

Given an n x n binary matrix image, we perform the following operations on each row of the matrix:

  1. Reverse the row.
  2. Invert the image (flipping 0 to 1 and 1 to 0).

Return the resulting image.

Clarifying Questions:

  1. Input Format: Can we assume that the input matrix contains only binary values (0s and 1s)?
    • Yes, the matrix contains only binary values.
  2. Size Constraints: Can we assume the matrix will always be square, i.e., n x n?
    • Yes, assume that the input matrix is always a square matrix.
  3. Output: Can I return a new matrix, or should the operations be in-place?
    • You can return a new matrix or modify the existing matrix in-place.

Strategy:

  1. Reverse Each Row: We need to reverse each row of the matrix.
  2. Invert Each Element: After reversing, we invert each element of the row (change 0 to 1 and 1 to 0).

To implement this, we can use a nested loop:

Strategy Steps:

  1. Traverse each row of the matrix.
  2. For each row, reverse it.
  3. Invert each element by simply applying 1 - value (since 1 - 0 gives 1 and 1 - 1 gives 0).

Example:

Given the input:

[[1,1,0],
 [1,0,1],
 [0,0,0]]

After reversing each row:

[[0,1,1],
 [1,0,1],
 [0,0,0]]

After inverting each element:

[[1,0,0],
 [0,1,0],
 [1,1,1]]

Code:

def flipAndInvertImage(image):
    for row in image:
        # Reverse the row and invert each element
        for i in range((len(row) + 1) // 2):
            # Simultaneously reverse and invert with a two-pointer approach
            row[i], row[~i] = 1 - row[~i], 1 - row[i]
    return image

# Example usage
image = [[1,1,0],[1,0,1],[0,0,0]]
print(flipAndInvertImage(image))

Time Complexity:

Thus, the total time complexity of this approach is O(n^2) where n is the number of rows or columns in the square matrix.

Try our interview co-pilot at AlgoAdvance.com