#1591

Strange Printer II

Hard
ArrayGraph TheoryTopological SortMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the idea of reverse engineering the printing process. By checking if each color can be the last printed color without conflicting with others, we can determine if the grid can be printed as specified.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a mapping of each color to its positions in the grid.
  2. 2Step 2: For each color, check if it can be the last printed color by ensuring that all its positions form a contiguous rectangle.
  3. 3Step 3: Ensure that no other colors occupy the rectangle that would invalidate the last print operation.
  4. 4Step 4: If all colors satisfy the conditions, return true; otherwise, return false.
solution.py26 lines
1# Full working Python code
2from collections import defaultdict
3
4def isPrintable(targetGrid):
5    m, n = len(targetGrid), len(targetGrid[0])
6    color_positions = defaultdict(list)
7
8    # Step 1: Map each color to its positions
9    for i in range(m):
10        for j in range(n):
11            color_positions[targetGrid[i][j]].append((i, j))
12
13    # Step 2: Check if each color can be the last printed
14    for color, positions in color_positions.items():
15        min_row = min(pos[0] for pos in positions)
16        max_row = max(pos[0] for pos in positions)
17        min_col = min(pos[1] for pos in positions)
18        max_col = max(pos[1] for pos in positions)
19
20        # Step 3: Validate the rectangle
21        for i in range(min_row, max_row + 1):
22            for j in range(min_col, max_col + 1):
23                if targetGrid[i][j] != color:
24                    return False
25
26    return True

Complexity note: The time complexity is O(n) because we efficiently check each color's positions and validate their rectangles in a single pass.

  • 1Understanding the constraints of the problem helps in devising a solution that respects the printing rules.
  • 2Visualizing the grid and the colors can reveal patterns that simplify the validation process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.