Narrowest column widths for spanning header cells

Write codeMedium25 min

Your task

A data grid sizes its columns to fit their content. Some header cells span several adjacent columns, like a "Q1" header over January, February and March. Every cell needs a minimum width to show its text without clipping.

Write narrowest_table(columns, cells) that returns the smallest total width the columns can have.

Input and output:

  • columns: the number of columns, from 1 to 1,000.
  • cells: up to 1,000 cells, each [first, span, width]. The cell covers the span columns that start at column first (columns count from 0), and it needs at least width pixels. span is at least 1, first + span is at most columns, and width is an integer from 0 to 1,000,000,000.
  • Returns an integer.

Rules:

  • Every column gets a whole number of pixels, 0 or more.
  • For every cell, the widths of the columns it covers add up to at least the cell's width.
  • Borders and padding are already included in the cell widths.
  • Return the smallest possible sum of all the column widths.

Examples

narrowest_table(columns: int, cells: list[list[int]]) -> int
Example 1
Inputnarrowest_table(3, [[0, 1, 80], [1, 1, 60], [2, 1, 70], [0, 3, 300]])
Output300
Example 2
Inputnarrowest_table(4, [[0, 2, 100], [1, 2, 100], [2, 2, 100]])
Output200
Example 3
Inputnarrowest_table(3, [[0, 1, 50], [0, 2, 120], [1, 2, 90]])
Output140