Google "On Site" Interview Question
Anonymous User
1812

Got the following as an interview question. It seems to be a derivative of 832. Flipping an Image. I call it Flipping an Image II.


Flipping an Image II

Problem Description

Given a grayscale image represented as a bytearray and its dimensions (width w and height h), write a function to flip the image horizontally in place. Each bit in the bytearray represents a single pixel. The width w is given in bits and is guaranteed to be a multiple of 8.

The goal is to flip the image horizontally.

Function Signature

def flip_horizontally_in_place(image: bytearray, w: int, h: int) -> None:

Parameters

  • image (bytearray): A mutable sequence of bytes representing the image data, where each bit represents a single pixel.
  • w (int): The width of the image in bits (number of pixels per row).
  • h (int): The height of the image (number of rows).

Constraints

  • 8 <= w <= 10^4
  • 1 <= h <= 10^3
  • The total number of bytes in image is equal to (w * h) // 8.

Example

# Example input
image_data = bytearray([
    0b10100011, 0b00001111,  # Row 1: 10100011 00001111
    0b11110000, 0b11001010,  # Row 2: 11110000 11001010
    0b10010110, 0b01010101   # Row 3: 10010110 01010101
])
width = 16
height = 3

flip_horizontally_in_place(image_data, width, height)

# Expected Output: Each row's bits reversed
# Row 1 becomes: 11110000 11000101
# Row 2 becomes: 01010011 00001111
# Row 3 becomes: 10101010 01101001

print([f'{byte:08b}' for byte in image_data])
# Output: ['11000101', '11110000', '01010011', '00001111', '01101001', '10101010']

Note

  • You must perform the operations in place, without using extra space for another bytearray.
  • Think about optimizing both the time and space complexity.
  • Consider edge cases where the image width or height is at its minimum.

Explanation

  • Bit Manipulation: Directly manipulate the bits to reverse their order in each row.
  • Row Processing: Process each row independently, considering the width in bits.
Comments (4)