← Questions

Largest square from 1x1 and 2x2 tiles

0
MicrosoftCoding

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 + 4N overflow 64 bits? (No, but say so.)

What a strong answer covers

  • For a side s, at most (s // 2)^2 large tiles fit, so s works when s^2 - 4 * min(N, (s // 2)^2) <= M.
  • Points out that this test is not monotone in s: with M = 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 about 7 * 10^4 sides at most.
  • Uses integer square roots, not floats.
  • Tests all examples, M = 0, N = 4 (side 4), N = 0 (side isqrt(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

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