← Questions
Fewest changes to draw the letter Y in a grid
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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
-
nis 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 // 2and (c == rorc == n - 1 - r), orr >= n // 2andc == 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 ofb). - 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
- Databricks · Online assessment · Last asked Sep 2024Timed online coding test
What it tests
matrix · counting
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
