Ctrl K

A Table From Its Totals

Medium
All that is left of a table of non-negative integers are its totals: row_totals[i] is the sum of row i and col_totals[j] is the sum of column j. The numbers themselves are lost. Rebuild a len(row_totals) × len(col_totals) table with these totals. Many tables usually fit, so return a specific one: reading its cells row by row (the first row left to right, then the second, and so on) must give a sequence that is lexicographically larger than for any other fitting table. Put simply, each cell in turn gets the largest number it can. The sums of row_totals and col_totals are equal, so a fitting table always exists.
Example 1
row_totals=[5, 6], col_totals=[2, 9] → [[2, 3], [0, 6]]

The top-left cell gets the most it can, min(5, 2) = 2. The remaining 3 of the first row goes to the right, and the second row gets 0 and 6: [[2, 3], [0, 6]].

Example 2
row_totals=[4, 0, 3], col_totals=[3, 4] → [[3, 1], [0, 0], [0, 3]]

The zero row is all zeros; the result is [[3, 1], [0, 0], [0, 3]].

Example 3
row_totals=[7], col_totals=[1, 2, 4] → [[1, 2, 4]]

With a single row, every cell equals its column's total.

Constraints
  • 1 ≤ len(row_totals), len(col_totals) ≤ 500
  • 0 ≤ row_totals[i], col_totals[j] ≤ 10⁸
  • sum(row_totals) == sum(col_totals)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRaise Towers, Keep the Skyline MediumBest Binary Rows After Flips MediumTwo Rows of Lamps MediumRows Under the Diagonal MediumBiggest Block After a Column Shuffle Medium
loading Python…
Input
row_totals=[5, 6], col_totals=[2, 9]
Expected
[[2, 3], [0, 6]]

Run checks the first 3 tests in your browser. Submit checks all 43 tests on the server, hidden ones included.