Hard: Advanced Interview · Problem 75 of 82

Business Days

HardErrors and FilesPython

Write business_days(start, end) that counts the weekdays (Monday to Friday) from start to end, both dates included. The dates are text in the form "YYYY-MM-DD". If end is before start, return 0.

The tests include the whole range from year 1 to year 9999, so walking through the days one at a time is too slow.

Understand the problem

Learn the date tools.

What does datetime.date(2024, 3, 4).weekday() return? (March 4, 2024 is a Monday. weekday() counts Monday as 0.)

weekday() gives 0 for Monday up to 6 for Sunday. So Saturday is 5 and Sunday is 6: those are the days to skip.

How do you turn "2024-03-04" into a date object?

  1. date("2024-03-04")
  2. datetime.date.fromisoformat("2024-03-04")
  3. int("2024-03-04")

date.fromisoformat parses the YYYY-MM-DD form. (datetime.strptime(text, "%Y-%m-%d") does the same with an explicit format.)

Subtracting two dates, date(2024, 3, 11) - date(2024, 3, 4), gives what?

  1. A number 7
  2. A timedelta of 7 days; its .days is 7
  3. A date

Date arithmetic gives a timedelta. Use .days for the whole number of days, and add one to count both ends.

Write the brute force

Write the simplest version that is correct, even if it is slow. Then you have something to test against and something to improve.

def business_days(start, end):
    # Write the simple version here. It only has to be correct, not fast.
    pass
Hint 1: a question to ask yourself

How can you visit every day from the start to the end?

Hint 2: the shape of the answer

Parse both dates. Starting at start, add timedelta(days=1) repeatedly while the day is not after end, and count the days whose weekday() is below 5.

Find the bottleneck

How much work is that?

From year 1 to year 9999 there are about 3.65 million days. Why is walking day by day slow?

  1. Dates are slow in Python
  2. Each step creates a date object and calls a method, millions of times
  3. The loop is infinite

About 3.65 million loop iterations, each making a new date and a method call: that takes seconds. The weekday pattern repeats every 7 days, so counting them one at a time is wasted work.

In any 7 consecutive days, how many are weekdays?

  1. 5
  2. 7
  3. It depends

Every block of 7 consecutive days holds exactly 5 weekdays, whatever day it starts on. So count the full weeks at once (5 each) and look at the few leftover days by hand.

Make it faster

Count whole weeks by arithmetic, then the leftover days.

def business_days(start, end):
    # Write the faster version here.
    pass
Hint 1: a question to ask yourself

How many days are there in total, and how many full weeks and leftover days does that make?

Hint 2: the pattern

days = (end - start).days + 1; weeks, extra = divmod(days, 7). The full weeks give weeks * 5. The extra days are the first extra days starting at start: count their weekdays by looking at them (at most 6).

Hint 3: pseudocode

days = (end - start).days + 1 if days <= 0: return 0 weeks, extra = divmod(days, 7) count = weeks * 5 for i in range(extra): # at most 6 days if (start + i days).weekday() < 5: count += 1 return count

Reflect

Brute force: one day at a time

from datetime import date, timedelta

def business_days(start, end):
    day = date.fromisoformat(start)
    last = date.fromisoformat(end)
    count = 0
    while day <= last:
        if day.weekday() < 5:
            count += 1
        day += timedelta(days=1)
    return count

Improved: full weeks by arithmetic

from datetime import date, timedelta

def business_days(start, end):
    first = date.fromisoformat(start)
    last = date.fromisoformat(end)
    days = (last - first).days + 1
    if days <= 0:
        return 0
    weeks, extra = divmod(days, 7)
    count = weeks * 5
    for i in range(extra):
        if (first + timedelta(days=i)).weekday() < 5:
            count += 1
    return count

What this tests: the datetime module (date, timedelta, fromisoformat, weekday), divmod, and replacing a long loop with arithmetic.

The pattern: when something repeats with a fixed period (a week), count the full periods with arithmetic and handle only the remainder by hand. The same idea appears in clock arithmetic, calendars and modular counting problems.

Both ends included: the number of days from the 4th to the 8th is (8th - 4th).days + 1, five days. Forgetting the + 1 is the commonest off-by-one in date problems.

Real calendars have holidays. A real business-day function takes a list of holiday dates, or uses numpy.busday_count or the holidays package.

Cost:

Version Time
One day at a time O(number of days)
Full weeks and a remainder O(1)

What an interviewer might ask next: Add a list of holidays that must not be counted. (Subtract the holidays that fall on weekdays inside the range.)