DDSA Solutions

832. Flipping an Image

Time: O(n²)
Space: O(1)
Advertisement

Intuition

Reverse each row then flip each bit. Optimize: process two pointers from ends; if they're the same, flip both; if different, no-op (they're already flipped-inverted).

Algorithm

  1. 1For each row, use two pointers l and r. While l <= r: if A[l]==A[r], flip both (XOR with 1). If different, leave as-is (reverse+invert cancel out).

Example Walkthrough

Input: [[1,1,0],[1,0,1],[0,0,0]]

  1. 1.Row 0: [0,0,1]. Row 1: [0,1,0]. Row 2: [1,1,1].

Output: [[0,0,1],[0,1,0],[1,1,1]]

Common Pitfalls

  • The combined reverse-then-flip can be done in one pass. If outer pair equal, they become (1-val, 1-val). If different, they become (1,0) from (0,1) or (0,1) from (1,0) — unchanged.
832.cs
C#
// Approach: For each row, XOR both ends with 1 while swapping them inward; handles middle element in-place.
// Time: O(n²) Space: O(1)

public class Solution
{
    public int[][] FlipAndInvertImage(int[][] image)
    {
        int n = image[0].Length;

        foreach (int[] row in image)
        {
            for (int i = 0; i < (n + 1) / 2; i++)
            {
                int temp = row[i] ^ 1;
                row[i] = row[n - 1 - i] ^ 1;
                row[n - 1 - i] = temp;
            }
        }

        return image;
    }
}
Advertisement
Was this solution helpful?