Flipping an Image

You are given an `n x n` binary matrix `image`. Flip it horizontally, which reverses every row, and then invert it, which turns every `0` into `1` and every `1` into `0`. Return the resulting image. For example, flipping `[1,1,0]` gives `[0,1,1]`, and inverting that gives `[1,0,0]`.

30:00

Flipping an Image
easy
Free written solution
Topics
Companies

You are given an n x n binary matrix image. Flip it horizontally, which reverses every row, and then invert it, which turns every 0 into 1 and every 1 into 0. Return the resulting image.

For example, flipping [1,1,0] gives [0,1,1], and inverting that gives [1,0,0].

Example 1:
Input: {"image":[[1,1,0],[1,0,1],[0,0,0]]}
Output: [[1,0,0],[0,1,0],[1,1,1]]
Constraints:
  • n==image.lengthn == \text{image.length}

  • n==image[i].lengthn == \text{image}[i].\text{length}

  • 1≤n≤201 \leq n \leq 20

  • image[i][j]\text{image}[i][j] is 00 or 11

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"image":[[1,1,0],[1,0,1],[0,0,0]]}

Flip then invert can be done in one pass: walk two pointers in from both ends of each row, swap the pair and invert both with ^ 1.

image (white = 1, black = 0), dashed line = mirror axis

r0

1
1
0

r1

1
0
1

r2

0
0
0

this step

swap the mirror pair, invert both

before

→

now

Variables
VariableValue
n3
DepthFunction Call
Stack empty
0/10