#### Category: Easy

**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]`

.

https://leetcode.com/problems/flipping-an-image/

**Examples:**

**Example 1**

1 2 3 4 | 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**

1 2 3 4 | 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]] |

**Constraints:**

`1 <= A.length = A[0].length <= 20`

`0 <= A[i][j] <= 1`

**Solution Approach**

Here we have flipping an image problem where we are given a binary 2D matrix and we have to flip and invert that matrix. The flip should take place horizontally i.e every row should be in reverse order and manipulation should be done on that reversed array.

We can try to reverse the whole matrix in one go and do the interchange of 0s and 1s afterwards but that will increase our time complexity hence it’s not worth it. What we can do is we can reverse the matrix rows one by one and perform the manipulation there itself thus saving us time and helping in reduce the time complexity.

Now my approach is to iterate through all the rows and clone one array and store it in a variable (clone in my example). Then I iterated through all the elements in a row and replaced each element in reverse order and also by changing the value i.e 0 becomes 1 and vice versa using ternary operator. Then returned the original matrix as the answer.

**Solution Code**

1 2 3 4 5 6 7 8 9 10 11 | class Solution { public int[][] flipAndInvertImage(int[][] A) { for(int i=0; i<A.length; i++){ int [] clone = A[i].clone(); for(int j=0; j<A[i].length; j++){ A[i][j] = clone[A[i].length-j-1]==1 ? 0 : 1; } } return A; } } |

For more Leetcode explained solutions visit Leetcode Solutions. If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via Contact page I will surely respond. Happy Leetcoding 🙂