↓Skip to main content
  1. LeetCode/

LeetCode 832: Flipping an Image

·2 mins· ·
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-15

  • Submissions: Runtime Error ×7 → Accepted

Approach
#

Reverse each row, then invert it. Two pointers do both at once (Two Pointers Template 1): swap row[l] and row[r] while applying ^ 1 to each; the middle cell with l == r is inverted once.

My Attempts
#

The first seven submissions were REs: attempt 1 computed the loop count with /, passing a float to range (TypeError); after switching to //, that version and the next five returned or iterated over a nonexistent A (the parameter is image, NameError). Attempt 1’s swap also used row[-i], which is off by one (row[-0] is row[0], not the last cell) and should be row[-1 - i]. A one-line list comprehension over image finally passed.

Solution
#

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        for row in image:
            l, r = 0, len(row) - 1
            while l <= r:
                row[l], row[r] = row[r] ^ 1, row[l] ^ 1
                l, r = l + 1, r - 1
        return image

Complexity
#

Time O(n²), space O(1).

Mistakes to Avoid
#

  • When l == r the simultaneous assignment inverts it once, which is correct.

Interview Explanation
#

For each row two pointers swap the ends while XOR-ing each with 1, inverting the middle cell once. Time O(n²), space O(1).

Related

LeetCode 821: Shortest Distance to a Character
·2 mins
LeetCode Easy Array Two-Pointers String
LeetCode 821 note: one left-to-right pass for the distance to the nearest c on the left, then a right-to-left pass taking the minimum
LeetCode 766: Toeplitz Matrix
·2 mins
LeetCode Easy Array Matrix
LeetCode 766 note: every diagonal is constant exactly when each cell equals its upper-left neighbor
LeetCode 733: Flood Fill
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 733 note: DFS or BFS from the start, recoloring 4-directional cells that share the start’s original color; return immediately if the colors are equal
LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 661: Image Smoother
·2 mins
LeetCode Easy Array Matrix
LeetCode 661 note: each cell becomes the floored average of the existing cells in its 3 × 3 neighborhood, written into a new matrix
LeetCode 566: Reshape the Matrix
·2 mins
LeetCode Easy Array Matrix Simulation
LeetCode 566 note: return the original if the element counts differ; otherwise element k goes to (k // c, k % c)