Given an n x n
binary matrix image
, we perform the following operations on each row of the matrix:
0
to 1
and 1
to 0
).Return the resulting image.
n x n
?
0
to 1
and 1
to 0
).To implement this, we can use a nested loop:
1 - value
(since 1 - 0
gives 1
and 1 - 1
gives 0
).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]]
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))
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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?