LeetCode 832: Flipping an Image

link

Horizontal flip of a row is like swapping the values at pairs of indices starting from the two ends going towards the center. So, if values of a pair of such indices are different, a flip followed by an invert behaves like two inverts in sequence — resulting in zero changes. Likewise, same values behaves like an invert. So, we actually have a single operation per pair of elements in a row.

Time: \mathcal{O}(n^2), space: \mathcal{O}(1)

class Solution:
    def flip_and_invert(self, row, n):
        left, right = 0, n-1
        while left < right:
            if row[left] == row[right]:
                row[left] = 1 - row[left]
                row[right] = 1 - row[right]
            left += 1
            right -= 1
        
        if left == right:
            # If a center exists, invert
            row[left] = 1 - row[left]

    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        n = len(image)
        for row in image:
            self.flip_and_invert(row, n)
        
        return image

Leave a comment