Flip and Invert Image

Mirror each row of a 0/1 image and swap its 0s and 1s, both in one pass over the row.

Given an n x n matrix image whose cells each hold 0 or 1, flip every row horizontally, then invert it, and return the resulting image. Flipping a row reverses it, so [1, 1, 0] becomes [0, 1, 1]. Inverting turns every 0 into 1 and every 1 into 0, so [0, 1, 1] becomes [1, 0, 0].

Example 1
Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Example 2
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Solution

The Idea

Imagine a tiny black-and-white image made of squares, where 1 is a black square and 0 a white one. Flipping holds the image up to a mirror, so each row now reads from right to left. Inverting turns it into a photo negative: black squares become white and white squares become black.

Look at the top half of the picture below, which takes Example 1 through both steps. Row 0 of the grid labelled "image" is 1, 1, 0. In the grid "after flipping each row" it reads 0, 1, 1, and in the grid "after inverting every cell" it reads 1, 0, 0, which is row 0 of the expected output.

Top: Example 1 as three grids with row and column numbers: the image, after flipping each row, and after inverting every cell. Row 0 goes from 1 1 0 to 0 1 1 to 1 0 0. Bottom: row 1, which is 1 0 1, done in one pass. i starts at col 0 and j at col 2, the pair 1 and 1 is swapped and inverted to 0 and 0, then i and j meet at col 1 and its 0 is inverted to 1.

Done that way, every row is walked twice, once to reverse it and once to invert it. Could one walk do both? Look at where each value in the last grid came from. The 1 in row 0, col 0 is the 0 that sat in row 0, col 2 of the image, inverted. So every cell of the answer is the cell at the mirror position in the same row, inverted.

Pairing each cell with its mirror suggests walking in from both ends of a row at once. Keep one marker, i, on the leftmost cell not yet handled and another, j, on the rightmost. The two cells they point at trade places and are both inverted on the way, then the markers step toward each other.

The bottom half of the picture does this for row 1, which is 1, 0, 1. In the box labelled "start", i is at col 0 and j at col 2. Their pair, 1 and 1, is swapped and inverted, so in the middle box it has become 0 and 0. Now both markers stand on col 1, marked "i = j", the middle cell. It has no partner and stays in place, but it still has to be inverted, so its 0 becomes 1. The row reads 0, 1, 0, row 1 of the expected output.

Pairing the leftmost and rightmost cells that are still open, and moving the two markers inward until they meet, is often called the two-pointer method; here the two pointers are just the column numbers i and j.

Solution Approach

Turning that idea into code means settling three things: inverting one cell, handling a pair of cells from the two ends, and the middle cell of a row with an odd number of cells. There is also an optional shortcut that leaves some pairs alone.

Inverting one cell

How do we turn a 0 into 1 and a 1 into 0? Writing 1 - x works, and so does the bit operation XOR, written ^ in Java. XOR compares two numbers bit by bit and sets a bit to 1 where exactly one of the two numbers has a 1 there.

A cell is a Java int, which has 32 bits, numbered from position 0 on the right. A cell holding 1 is 000...0001 in binary, with only position 0 set, and a cell holding 0 has no bit set at all. The number 1 also has only position 0 set, so XOR with 1 flips position 0 and leaves the other 31 bits at 0. That gives 0 ^ 1 = 1 and 1 ^ 1 = 0.

Swapping and inverting a pair

Why not reverse the row first and then invert it? That also gives the right answer in the same order of time, but it walks the row twice. The pair step does both at once: save the left cell, inverted, in a variable named left. Then write the right cell, inverted, into the left position, and write left into the right position.

The variable left is needed because writing into the left position first overwrites its old value, and the right position still needs it.

The middle cell

What happens when a row has an odd number of cells, like the rows of Example 1? After the outer pairs are done, i and j land on the same middle column. The loop keeps going while i <= j, so it runs one more step with i == j. In that step left holds the middle cell inverted, and both writes put that same inverted value back into the one cell, so the cell is inverted exactly once.

For an even number of cells, as in Example 2, the markers pass each other without meeting, and every cell belongs to a pair.

Skipping pairs that differ

Take a pair that differs, such as 1 on the left and 0 on the right. Swapping gives 0 and 1, and inverting gives 1 and 0 again, so the pair ends up as it started. A pair with equal values does change: 1 and 1 become 0 and 0, and 0 and 0 become 1 and 1.

As an optional improvement, the loop can invert both cells only when row[i] == row[j] and leave differing pairs alone. The middle cell always equals itself, so it is still inverted. Checked against the main solution on 10,000 random images, this version gave the same result every time. The order of time stays the same, since every pair still has to be compared.

Java Solution

The method flipAndInvertImage works in these steps:

  1. A for-each loop takes the rows of image one at a time, as row. The cells are changed in place, so no new matrix is made.
  2. For each row, set i to 0, the first column, and j to row.length - 1, the last column.
  3. Inside, a while loop runs as long as i <= j. It saves row[i] ^ 1 in left, writes row[j] ^ 1 into row[i], and writes left into row[j]. Then i moves one column right and j one column left.
  4. When every row is done, the method returns image, which now holds the answer.

The main method runs both examples, two images of a single cell (one holding 0, one holding 1), and a 2 x 2 image whose rows are both pairs that differ. A small helper, show, prints a label and then the image row by row.

Java
import java.util.Arrays;

public class FlipAndInvertImage {

    public static int[][] flipAndInvertImage(int[][] image) {
        for (int[] row : image) {
            int i = 0;
            int j = row.length - 1;
            while (i <= j) {
                int left = row[i] ^ 1;     // the left value, inverted
                row[i] = row[j] ^ 1;       // the right value, inverted, moves left
                row[j] = left;             // the left value, inverted, moves right
                i++;
                j--;
            }
        }
        return image;
    }

    static void show(String label, int[][] image) {
        System.out.println(label);
        for (int[] row : image) {
            System.out.println("  " + Arrays.toString(row));
        }
    }

    public static void main(String[] args) {
        show("Example 1:", flipAndInvertImage(new int[][] {{1, 1, 0}, {1, 0, 1}, {0, 0, 0}}));
        show("Example 2:", flipAndInvertImage(new int[][] {
            {1, 1, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 1}, {1, 0, 1, 0}}));
        show("One cell, 0:", flipAndInvertImage(new int[][] {{0}}));
        show("One cell, 1:", flipAndInvertImage(new int[][] {{1}}));
        show("Mixed pairs:", flipAndInvertImage(new int[][] {{1, 0}, {0, 1}}));
    }
}

Running it prints:

Output
Example 1:
  [1, 0, 0]
  [0, 1, 0]
  [1, 1, 1]
Example 2:
  [1, 1, 0, 0]
  [0, 1, 1, 0]
  [0, 0, 0, 1]
  [1, 0, 1, 0]
One cell, 0:
  [1]
One cell, 1:
  [0]
Mixed pairs:
  [1, 0]
  [0, 1]

Under "Example 1:", the middle line [0, 1, 0] is row 1 from the bottom half of the picture, with its middle 0 turned into 1. The rows under "Example 2:" match the expected output too, and there every cell was part of a pair.

The single cells come out as [1] and [0]. With one column, i and j both start at 0, and the i <= j check lets that one step run. Under "Mixed pairs:", [1, 0] and [0, 1] come back exactly as they went in, because each row is a pair that differs.

That <= matters. With while (i < j) instead, Example 1 returns [[1, 1, 0], [0, 0, 0], [1, 0, 1]]: every middle cell keeps its old value, because the loop stops before i and j meet.

Complexity

Each cell is handled in one step of the loop, and the work needs no storage beyond three numbers.

  • Time: O(n2), because the image has n rows of n cells, and in each row the markers cover all n cells in about n / 2 steps of two cells each.
  • Space: O(1), because the image is changed in place and each row needs only i, j and left.

Markers that move in from both ends of an array come up in many other problems; see Two Pointers.