Largest square from 1x1 and 2x2 tiles
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests math, binary-search and geometry.
You have M small tiles of size 1×1 and N large tiles of size 2×2. Build the largest possible square: every cell of the square must be covered by exactly one tile, with no gaps, no overlaps, and no tile sticking out past the edge. You do not have to use all of your tiles.
Implement:
def max_square_side(m: int, n: int) -> int: ...
Return the side length of the largest square you can build, or 0 if you cannot build any square.
Constraints
0 <= M, N <= 1_000_000_000- Aim for better than linear time in
M + N.
Example 1
M = 5, N = 1 returns 3. Put the 2×2 tile in one corner of a 3×3 square and fill the remaining 5 cells with 1×1 tiles.
Example 2
M = 0, N = 3 returns 2. The tiles have total area 12, but three 2×2 tiles cannot fill a 3×3 square (area 9 is not a multiple of 4) and a 4×4 square needs four of them. One 2×2 tile alone makes a 2×2 square.
Example 3
M = 0, N = 0 returns 0.
Clarifying questions
- Must the 2x2 tiles sit on a grid of even cells, or anywhere? (Placement does not change the count that fits.)
- Is a square of side 1 from one small tile valid?
- Do we need the tile layout, or only the side?
- Can
M + 4Noverflow 64 bits? (No, but say so.)
What a strong answer covers
- For a side
s, at most(s // 2)^2large tiles fit, sosworks whens^2 - 4 * min(N, (s // 2)^2) <= M. - Points out that this test is not monotone in
s: withM = 0, N = 4, side 4 works but side 3 does not. A single binary search over all sides is wrong. - Searches even sides and odd sides separately, since each is monotone, or tries every side up to
isqrt(M + 4N). That is about7 * 10^4sides at most. - Uses integer square roots, not floats.
- Tests all examples,
M = 0, N = 4(side 4),N = 0(sideisqrt(M)) and very large values.
Follow-ups
- Build the largest rectangle instead of a square.
- Add 3x3 tiles.
- Use the fewest tiles for the largest square.
- Return one valid layout.
Where it's asked
What it tests
math · binary-search · geometry
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
