1431. Grid Rectangle Census

Easy1.5 points estimatedCombinatoricsMathsBrainteaser

A tiling designer has a floor made of unit square cells arranged in rows rows and cols columns, and wants to know how many different rectangular patches can be outlined along the cell edges. Count every axis-aligned rectangle that consists of whole cells, of any width and height, squares and single cells included, and return the count. A rectangle is fixed by choosing two of the rows + 1 horizontal grid lines and two of the cols + 1 vertical grid lines, so the count is a product of two binomial coefficients. The expected time is O(1) with O(1) extra space, and the answer needs 64-bit arithmetic.

Example 1

Input:
rows = 2, cols = 2
Output:
9
Explanation:

A 2 by 2 grid has 4 single cells, 4 dominoes, 1 full square, 9 rectangles in total (3 * 3).

Example 2

Input:
rows = 1, cols = 3
Output:
6
Explanation:

A single row of 3 cells has 3 + 2 + 1 = 6 rectangles.

Constraints

1 ≤ rows, cols ≤ 104
The answer is at most 2.6 * 1015.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(1)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…