Interview Questions/Coding/Repaint The Grid

Repaint The Grid

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Repaint The Grid

You are given an n x m grid where each cell contains one of the letters A, B, C, or D. You must repaint every cell using one of these four letters. The new letter of a cell must be different from its original letter. After repainting, no two adjacent cells that share an edge should contain the same letter. To make the output deterministic, follow this exact rule: Scan the grid row by row from top to bottom, and within each row from left to right. For every cell, choose the lexicographically smallest letter from A, B, C, D that is different from: 1. the original letter in that cell, 2. the already repainted cell directly above it, if it exists, 3. the already repainted cell directly to its left, if it exists. Return the final repainted grid.

Examples

Example 1
Input:
3 4
AAAA
BBBB
CCDD
Output:
BCBC

Explanation: ADAD BABA

Approach hint

Only the top and left cells have already been repainted when processing a cell.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp