← Questions

Fewest changes to draw the letter Y in a grid

0
DatabricksCodingLast asked Sep 2024

A coding interview question asked in Databricks's online assessment, last asked Sep 2024. It tests matrix and counting.

An n × n grid, with n odd, holds only the values 0, 1 and 2. The letter Y is made of the two diagonals from the top corners down to the centre, plus the centre column from the centre down to the bottom. To write the Y, every Y cell must hold one value and every other cell a different value. Return the fewest cells you must change.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • min_changes_for_y(grid: list[list[int]]) -> int

Example

min_changes_for_y([[1, 0, 2],
                   [1, 2, 0],
                   [0, 2, 0]])                 ->  2    # Y = 2, background = 0: change (0,0) and (1,0)

min_changes_for_y([[2, 0, 0, 0, 2],
                   [1, 2, 1, 2, 0],
                   [0, 1, 2, 1, 0],
                   [0, 0, 2, 1, 1],
                   [1, 1, 2, 1, 1]])           ->  8    # Y = 2, background = 1: change the eight 0s

Constraints

  • n is odd, up to 99. Values are 0, 1 or 2.

Clarifying questions

  • Does the Y include the centre cell once (it is on both diagonals and the column)?
  • Must the Y value and the background value differ? (Yes.)
  • Are the values always 0–2, or could there be more?

What a strong answer covers

  • A clean test for "is (r, c) on the Y": r <= n // 2 and (c == r or c == n - 1 - r), or r >= n // 2 and c == n // 2.
  • One pass that counts each value inside and outside the Y.
  • Trying all six ordered pairs of distinct values: changes = (Y cells − Y count of a) + (other cells − other count of b).
  • O(n^2) time, O(1) extra space.
  • Tests: the smallest grid, a grid that already shows a Y, a grid of one value.

Follow-ups

  • Values range from 0 to k − 1. How do you choose the best pair without trying all k^2 pairs?
  • Draw any letter given as a mask of cells.
  • Return the grid after the changes.

Where it's asked

What it tests

matrix · counting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding