Biggest Square of Tiles

Easy · Binary Search · about 12 min

You have n identical square floor tiles, each 1 by 1. You want to lay the largest possible square of tiles, k tiles wide and k tiles long, using at most n tiles. Return k.

In other words, return the largest whole number k with k * k <= n. Do not use a square root function or a power of 0.5: find k with binary search.

Example: square_tile_side(10) → 3 (a 3 by 3 square uses 9 tiles; 4 by 4 would need 16)

Constraints: 0 <= n <= 2,147,483,647.

Hints

  • If a k by k square fits, every smaller square fits too. That yes-then-no shape is what binary search needs.
  • Search k between 0 and n. For the middle value, check whether its square is at most n.
  • If it fits, the answer is mid or bigger; if not, it is smaller. At the end, the high end of the range is the last side that fits.

Learn the pattern first: the Binary Search lesson.

More Binary Search problems