← Questions

Shortest equal length for two boards covering every hole

0

A coding interview question asked at Microsoft and Meta. It tests sorting, binary-search and greedy.

A table top has holes at integer positions along a single line, given as an unsorted array holes (positions may repeat or be negative). You will patch it with exactly two boards that must have the same positive integer length L. A board placed at position X covers every hole whose position is in [X, X + L], both ends included. Boards may be placed anywhere and may overlap.

Implement min_board_length(holes: list[int]) -> int that returns the smallest L for which all holes can be covered.

Constraints

  • 1 <= len(holes) <= 10^5
  • -10^9 <= holes[i] <= 10^9
  • Aim for O(n log n) time.

Example 1

holes = [3, 9, 4]
output: 1

One board covers [3, 4], the other covers [9, 10].

Example 2

holes = [0, 4, 5, 9, 10, 14]
output: 5

Boards at [0, 5] and [9, 14]. Splitting at another gap of 4 would leave one board needing length 10.

Clarifying questions

  • If one board can cover every hole with length 0 (all holes at one point), is the answer 1, since L must be positive?
  • Can the two boards overlap or sit at the same place? (Yes.)
  • Is a repeated hole position one hole or two? (It does not change the answer.)
  • Should we return where to place the boards?

What a strong answer covers

  • Sorts the holes. Some optimal pair of boards covers a prefix and a suffix of the sorted list.
  • For each split point, the length needed is the larger span of the two parts. The answer is the smallest such value, but at least 1. That is O(n log n) for the sort and O(n) for the scan.
  • Or binary searches on L with a greedy check, and says why the split scan is simpler.
  • Tests both examples, a single hole, all holes equal, two holes far apart, and negative positions.

Follow-ups

  • Use k boards: binary search on L with a greedy check.
  • The two boards may have different lengths, and we minimize their sum.
  • Return the board positions.
  • Holes on a 2D table, with square patches.

Where it's asked

What it tests

sorting · binary-search · greedy

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