Skip to content
Coding · Easy · Forecasting · Target O(n) · Mid

Days until the disk is full

Fit a straight line through disk-usage samples and return the whole days left before it reaches a threshold, or None when usage is flat or falling.

Statement

samples is a list of (timestamp, used_bytes) pairs of integers, timestamps in Unix seconds, in any order. Fit a least-squares straight line through them and write days_until_full(samples, threshold) that returns how many whole days after the latest sample's timestamp that line reaches threshold.

The slope of the line is (n·Σtu − Σt·Σu) ÷ (n·Σt² − (Σt)²), and the line passes through the mean point (Σt ÷ n, Σu ÷ n).

A day is 86,400 seconds. Round down: 6.8 days is 6, because overstating the time left is the costly mistake. If the line is already at or above threshold at the latest timestamp, return 0. Return None when there is no fill date: fewer than two samples, every sample at the same timestamp, or a line that is flat or falling.

Measure from the line, not from the last reading. Real timestamps are around 1.7 × 10⁹, so their squares do not fit exactly in a float. Python integers do not overflow: keep the sums as integers and divide once, at the end.

Examples

DAY = 86400

samples = [(0, 100), (DAY, 110), (2*DAY, 120), (3*DAY, 130)], threshold = 200
→ 7       # 10 a day, and 70 to go from the latest sample

samples = [(0, 100), (DAY, 125), (2*DAY, 115), (3*DAY, 140)], threshold = 195
→ 5       # slope 11 a day; the line is at 136.5 on day 3; 58.5 ÷ 11 = 5.3

samples = [(0, 100), (DAY, 100), (2*DAY, 100)], threshold = 200
→ None

Constraints

Up to 10⁵ samples. Timestamps may repeat. used_bytes and threshold are non-negative integers up to 10¹⁵. Return an int or None, never a float.

Free to try · sign in to save your attemptSolve it in the editor with visible tests
Open in the app