Katkat

Rotate a 3×3 digit grid by 180°

MicrosoftSoftware Engineer · Onsite

Last updated

This problem tests your ability to perform spatial transformations on a fixed-size 2D structure while maintaining data integrity across a transformation.

Problem Statement

You are given a 3x3 grid represented as a list of strings, where each string contains three digits (0-9). Your task is to rotate the entire grid 180 degrees.

A 180-degree rotation is equivalent to reversing the order of the rows and then reversing the order of the characters within each row. Alternatively, the character at coordinate (r, c) (0-indexed) moves to (2-r, 2-c).

Function Signature

def rotate_grid_180(grid: list[str]) -> list[str]:
    pass

Constraints

  • grid will always be a list of 3 strings.
  • Each string in grid will always contain exactly 3 digits.

Examples

Example 1: Input:

[
  "123",
  "456",
  "789"
]

Output:

[
  "987",
  "654",
  "321"
]

Explanation: The element at (0,0) '1' moves to (2,2). The element at (0,1) '2' moves to (2,1), and so on.

Example 2: Input:

[
  "000",
  "111",
  "222"
]

Output:

[
  "222",
  "111",
  "000"
]

Edge Cases

  • Grids with all identical digits.
  • Grids where the center element is the same after rotation (e.g., '5' in a 3x3 grid).

Hints

Hint 1

Consider the coordinate transformation where the element at row r and column c moves to position (2-r, 2-c).

Hint 2

Alternatively, you can achieve a 180-degree rotation by reversing the list of strings and then reversing the characters within each individual string.

Hint 3

Ensure you handle the string immutability in languages like Python by building new strings rather than attempting in-place modification.

Follow-up questions

  • How would you modify your solution to handle an N x N grid of arbitrary size?
  • What is the time and space complexity of your approach, and can it be optimized if the grid size is extremely large?
  • If the grid could contain non-digit characters, would your logic change? Why or why not?