Flipping an Image Solution in Java

Language Options

C++ Solution |
Python Solution

Code Solution


class Solution {
  public int[][] flipAndInvertImage(int[][] A) {
    final int n = A.length;

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < (n + 1) / 2; ++j) {
        final int temp = A[i][j];
        A[i][j] = A[i][n - j - 1] ^ 1;
        A[i][n - j - 1] = temp ^ 1;
      }

    return A;
  }
}

Problem Description

So, you think flipping an image is as easy as flipping a pancake? Well, think again! The problem at hand is to flip a binary image represented as a 2D array and then invert it. Imagine you have a picture of your favorite food, and you want to flip it upside down and then turn it into a black-and-white masterpiece. That's what this problem is all about!

In simpler terms, given a 2D array where each element is either 0 (representing white) or 1 (representing black), you need to flip the image horizontally and then invert it. So, if you had a row like [1, 0, 0], after flipping and inverting, it would become [1, 1, 0]. Easy, right? Well, not so fast!

Approach

The code provided takes a 2D array and iterates through each row. For each element in the row, it swaps the element with its corresponding element from the end of the row while also inverting the values. The XOR operation (^ 1) is a neat trick to flip the bits: it turns 0s into 1s and 1s into 0s.

Time and Space Complexity

Complexity Details
Time Complexity O(n2), where n is the number of rows (or columns, since it's a square matrix). We traverse each element of the matrix once.
Space Complexity O(1), as we are modifying the input matrix in place and not using any additional data structures.

Real-World Example

Think of it like taking a selfie and then flipping it upside down. You want to show your friends how you look from a different angle, but you also want to make sure that your face is not the only thing they see—let's add some fun by turning your smile into a frown! This problem is just like that—flipping and inverting an image to create a new perspective.

Similar Problems

If you enjoyed this problem, you might also want to check out these related challenges: