Problems / Business Days Between / Editorial
Instead of iterating over each date range, count weekdays from a single fixed anchor and subtract.
DATE '2000-01-03'
d
days = datediff('day', anchor, d) + 1
[anchor, d]
5 * (days // 7)
days % 7
least(days % 7, 5)
f(d) = 5 * (days // 7) + least(days % 7, 5)
(order_date, delivery_date]
f(delivery_date) - f(order_date)
Sanity checks: Friday order, Monday delivery -> 1 (only the Monday). Saturday order, Sunday delivery -> 0. Monday order, same-week Friday delivery -> 4 (Tue, Wed, Thu, Fri).
This is the *prefix-sum trick* applied to calendars: any "count X between a and b" problem becomes trivial if you can compute "count X from a fixed origin up to d" in closed form. Anchoring the origin on a Monday is what makes the closed form simple — the days % 7 remainder always starts the week, so its weekday count is just least(remainder, 5). The same idea powers np.busday_count in NumPy, which is how the expected output is verified independently.
least(remainder, 5)
np.busday_count
Solve Business Days Between yourself →