### LeetCode - Flipping an Image Solution - The Coding Shala

Home >> LeetCode >> Flipping an Image

In this post, we will learn how to solve the Flipping an Image problem and will implement Flipping an Image solution in Java.

## Flipping an Image Problem

Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [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]]

Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].

Then, invert the image: [[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]]

Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].

Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

Solve this problem on LeetCode: Click Here

## Flipping an Image Java Solution

**Approach 1:**

Either we can use addition array or ArrayList to reverse and invert numbers then return. Here will do in the same array without using any additional space.

If we reverse and invert the numbers at positions array[index] and array[length-index-1] then we get the same numbers at both positions, so we need to check only when both numbers are the same.

**Java Program:**

class Solution { public int[][] flipAndInvertImage(int[][] A) { int len = A.length; for(int i=0; i<len; i++) { for(int j = 0; j * 2 < len; j++) { //reverse and invert here //if j and len-j not same then after reverse //and invert will get same value if(A[i][j] == A[i][len-j-1]) { A[i][j] ^= 1; A[i][len-j-1] = A[i][j]; } } } return A; } }

**Other Posts You May Like**- LeetCode - Consecutive Characters
- LeetCode - Minimum Cost to Move Chips to the Same Position
- LeetCode - Buddy Strings
- LeetCode - Crawler Log Folder
- LeetCode - Convert Binary Number in a Linked List

## Comments

## Post a Comment