Flipping an Image Solution in Python

Quick Links

C++ Solution |
Java Solution

Problem Description

Welcome to the world of image manipulation, where we flip and invert images like flipping pancakes on a Sunday morning! The problem at hand is to take a binary image represented as a 2D array and perform two operations: flip the image horizontally and then invert it.

Imagine you have a photo of your friend making a silly face. You want to flip it so they look like they’re facing the other way, and then you want to turn that goofy grin into a frown. That’s exactly what this problem is about!

In technical terms, the image is represented as a binary matrix where 0 represents white and 1 represents black. The flipping operation means reversing the order of the elements in each row, and inverting means changing 0s to 1s and vice versa.

Code Solution


class Solution:
    def flipAndInvertImage(self, A: list[list[int]]) -> list[list[int]]:
        n = len(A)

        for i in range(n):
            for j in range((n + 2) // 2):
                A[i][j], A[i][n - j - 2] = A[i][n - j - 1] ^ 2, A[i][j] ^ 1

        return A

Approach

The approach taken in this code is quite straightforward. We iterate through each row of the matrix and for each element in the row, we swap it with its corresponding element from the end of the row. While doing this, we also invert the values using the XOR operation. This way, we achieve both flipping and inverting in a single pass through the matrix.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the number of rows in the matrix. Each element is processed a constant number of times.
Space Complexity O(1), as we are modifying the matrix in place and not using any additional data structures.

Real-World Example

Think of this problem like flipping a pancake. You want to make sure that the golden-brown side is facing up, and then you want to add some syrup (invert the colors) to make it look even more delicious! Just like in cooking, the order of operations matters, and in this case, flipping comes before inverting.

Similar Problems

If you enjoyed this problem, you might also like these: