Calculate Working Days Between Dates

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement count_business_days(start_date, end_date, holidays) to compute how many working days occur within the closed calendar interval [start_date, end_date].

A calendar date counts as a working day when both conditions hold:

  1. It falls on Monday, Tuesday, Wednesday, Thursday, or Friday (Saturdays and Sundays never count).
  2. It does not appear in holidays.

Every date argument is formatted as an ISO 'YYYY-MM-DD' string:

def count_business_days(start_date: str, end_date: str, holidays: List[str]) -> int:

Handle the following boundary rules:

  • Both start_date and end_date are included in the interval when start_date <= end_date (when start_date == end_date, the interval covers that single calendar day).
  • When start_date comes chronologically after end_date, the interval is empty and the function must return 0.
  • Entries in holidays may land on weekends, appear outside [start_date, end_date], or repeat the same date multiple times; each distinct weekday holiday inside the interval reduces the count by 1, while weekend and out-of-window holidays have no effect.

Examples

Example 1

Input:  start_date = "2025-05-01", end_date = "2025-05-09", holidays = ["2025-05-05", "2025-05-03"]
Output: 6

Walk-through: Thursday 2025-05-01 through Friday 2025-05-09 spans 9 calendar days containing 7 Monday–Friday dates (May 1, 2, 5, 6, 7, 8, 9). Monday 2025-05-05 is a weekday holiday and removes 1 working day, whereas Saturday 2025-05-03 falls on a weekend and is already excluded, leaving 6.

Example 2

Input:  start_date = "2025-09-06", end_date = "2025-09-21", holidays = ["2025-09-01"]
Output: 10

Walk-through: Saturday 2025-09-06 through Sunday 2025-09-21 spans 16 calendar days containing two full Monday–Friday workweeks (Sep 8–12 and Sep 15–19, totaling 10 weekdays). Monday 2025-09-01 precedes start_date, so all 10 weekdays remain working days.

Constraints

  • All dates in start_date, end_date, and holidays are valid Gregorian calendar dates formatted as 'YYYY-MM-DD'.
  • The span between start_date and end_date can cover decades or centuries, including leap years.
  • 0 <= len(holidays) <= 10^5.

Step-by-step walkthrough

  1. Restate the problem and edge-case rules

    We are given two 'YYYY-MM-DD' date strings (start_date and end_date) and a list of 'YYYY-MM-DD' holiday strings. We need to count how many calendar dates d in the inclusive range start_date <= d <= end_date satisfy both rules:

    1. d falls on Monday through Friday (not Saturday or Sunday).
    2. d is not listed in holidays.

    Three rules govern the tricky cases:

    • Holidays on weekends: If a holiday falls on Saturday or Sunday, that day was already excluded as a weekend—we must not subtract it again.
    • Duplicate or out-of-range holidays: holidays may repeat the same date or list dates outside [start_date, end_date]. Duplicates count at most once, and out-of-range dates have zero effect.
    • Start date after end date: The statement flags start_date > end_date as an edge case without specifying a return value; treating an inverted range as empty and returning 0 is the standard convention.
  2. Brute force: step through one day at a time

    Python's datetime.date type handles leap years and month lengths automatically. Calling date.fromisoformat("2025-05-01") builds a date object, and calling .weekday() returns an integer from 0 (Monday) through 6 (Sunday), so weekdays are simply .weekday() < 5.

    The most direct solution puts all holiday dates into a set and walks from start to end one day at a time:

    from datetime import date, timedelta
    
    
    def count_business_days_brute(start_date: str, end_date: str, holidays: list[str]) -> int:
        start = date.fromisoformat(start_date)
        end = date.fromisoformat(end_date)
        unique_holidays = {date.fromisoformat(h) for h in holidays}
    
        business_days = 0
        current = start
        while current <= end:
            if current.weekday() < 5 and current not in unique_holidays:
                business_days += 1
            current += timedelta(days=1)
        return business_days
    

    If the range spans D days and holidays has H entries, this takes O(D + H) time. Walking a few years is only a few thousand loop steps, which works for a one-off call, but a 100-year span takes 36,525 steps even when holidays is empty. We can compute the weekday count in O(1) time regardless of how many years separate start and end.

  3. Key idea: full 7-day weeks plus up to 6 leftover days

    Any 7 consecutive calendar days visit Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday once each—no matter which day of the week you begin on. That means every complete 7-day block contributes 5 weekdays.

    Suppose total_days is the inclusive number of days from start to end:

    • full_weeks = total_days // 7 complete blocks give full_weeks * 5 weekdays immediately.
    • leftover_days = total_days % 7 (at most 6 days) sit right after those full weeks.

    Which day of the week do those leftover days start on? Because they begin 7 * full_weeks days after start—an exact multiple of 7 days later—the first leftover day has the exact same weekday as start:

    Example: 10-day range starting on Wednesday (start.weekday() == 2)
    
    Day index:   0    1    2    3    4    5    6  |  7    8    9
    Weekday:    Wed  Thu  Fri  Sat  Sun  Mon  Tue | Wed  Thu  Fri
                \____________ 1 full week _______/  \_ 3 leftover _/
                      5 weekdays                      starts on Wed!
    

    So if start_weekday = start.weekday(), leftover day offset (for offset = 0, 1, ..., leftover_days - 1) has weekday (start_weekday + offset) % 7. The % 7 wraps Sunday (6) cleanly back around to Monday (0).

  4. Count weekdays in O(1) time

    Subtracting two Python date objects gives a timedelta whose .days attribute is the gap between them. For example, (date(2025, 5, 1) - date(2025, 5, 1)).days is 0, so we add 1 to count both endpoints.

    from datetime import date
    
    
    def count_weekdays(start: date, end: date) -> int:
        """Count Monday-through-Friday dates from start to end (both endpoints included)."""
        # Add 1 because the date range [start, end] is inclusive on both ends.
        total_days = (end - start).days + 1
        if total_days <= 0:
            return 0
    
        # Phase 1: Every complete 7-day chunk contains Monday..Sunday once, so 5 weekdays.
        full_weeks = total_days // 7
        weekday_count = full_weeks * 5
    
        # Phase 2: Check the remaining 0..6 days after all full 7-day chunks.
        # Stepping forward by 7 * full_weeks days lands on the exact same weekday as `start`.
        leftover_days = total_days % 7
        start_weekday = start.weekday()  # Monday = 0, ..., Friday = 4, Saturday = 5, Sunday = 6
        for offset in range(leftover_days):
            current_weekday = (start_weekday + offset) % 7
            if current_weekday < 5:
                weekday_count += 1
    
        return weekday_count
    

    Because leftover_days is strictly less than 7, the for loop runs at most 6 times—even for a 1,000-year range.

  5. Deduplicate and subtract weekday holidays in range

    Once we know how many Monday–Friday dates lie in [start, end], we only need to remove the ones that are holidays. A holiday should reduce the count by 1 if and only if:

    1. We have not already subtracted that same date (handled by storing parsed date objects in a set),
    2. It falls inside the window (start <= holiday <= end), and
    3. It falls on Monday through Friday (holiday.weekday() < 5), meaning count_weekdays actually counted it.
    from typing import List, Set
    from datetime import date
    
    
    def count_business_days(start_date: str, end_date: str, holidays: List[str]) -> int:
        start = date.fromisoformat(start_date)
        end = date.fromisoformat(end_date)
        if start > end:
            return 0
    
        business_days = count_weekdays(start, end)
    
        # unique_holidays: set of datetime.date objects so duplicate strings are subtracted at most once.
        unique_holidays: Set[date] = set()
        for holiday_str in holidays:
            unique_holidays.add(date.fromisoformat(holiday_str))
    
        # Subtract only holidays that fall inside [start, end] AND on Monday..Friday (< 5),
        # because weekend holidays were never included in `business_days` in the first place.
        for holiday in unique_holidays:
            if start <= holiday <= end and holiday.weekday() < 5:
                business_days -= 1
    
        return business_days
    
  6. Trace both examples step by step

    Example 1: start_date = "2025-05-01" (Thursday), end_date = "2025-05-09" (Friday), holidays = ["2025-05-05", "2025-05-03"].

    total_days    = (2025-05-09 - 2025-05-01).days + 1 = 8 + 1 = 9
    full_weeks    = 9 // 7 = 1        -> weekday_count = 1 * 5 = 5
    leftover_days = 9 % 7  = 2, starting at Thursday (3):
      offsets 0..1 -> weekdays 3 (Thu), 4 (Fri) (both < 5) -> weekday_count = 5 + 2 = 7
    holidays:
      2025-05-05 (Monday, weekday 0): in [2025-05-01, 2025-05-09] and < 5 -> 7 - 1 = 6
      2025-05-03 (Saturday, weekday 5): weekday() < 5 is False            -> ignored
    

    Example 2: start_date = "2025-09-06" (Saturday), end_date = "2025-09-21" (Sunday), holidays = ["2025-09-01"].

    total_days    = (2025-09-21 - 2025-09-06).days + 1 = 15 + 1 = 16
    full_weeks    = 16 // 7 = 2       -> weekday_count = 2 * 5 = 10
    leftover_days = 16 % 7  = 2, starting at Saturday (5):
      offsets 0..1 -> weekdays 5 (Sat), 6 (Sun) (neither < 5) -> weekday_count = 10
    holiday 2025-09-01:
      before 2025-09-06 -> out of range, ignored -> business_days = 10
    

    Both traces match the expected outputs 6 and 10.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from datetime import date
    
    
    def count_weekdays(start: date, end: date) -> int:
        """Count Monday-through-Friday dates from start to end (both endpoints included)."""
        # Add 1 because the date range [start, end] is inclusive on both ends.
        total_days = (end - start).days + 1
        if total_days <= 0:
            return 0
    
        # Phase 1: Every complete 7-day chunk contains Monday..Sunday once, so 5 weekdays.
        full_weeks = total_days // 7
        weekday_count = full_weeks * 5
    
        # Phase 2: Check the remaining 0..6 days after all full 7-day chunks.
        # Stepping forward by 7 * full_weeks days lands on the exact same weekday as `start`.
        leftover_days = total_days % 7
        start_weekday = start.weekday()  # Monday = 0, ..., Friday = 4, Saturday = 5, Sunday = 6
        for offset in range(leftover_days):
            current_weekday = (start_weekday + offset) % 7
            if current_weekday < 5:
                weekday_count += 1
    
        return weekday_count
    
    
    def count_business_days(start_date: str, end_date: str, holidays: List[str]) -> int:
        start = date.fromisoformat(start_date)
        end = date.fromisoformat(end_date)
        if start > end:
            return 0
    
        business_days = count_weekdays(start, end)
    
        # unique_holidays: set of datetime.date objects so duplicate strings are subtracted at most once.
        unique_holidays: Set[date] = set()
        for holiday_str in holidays:
            unique_holidays.add(date.fromisoformat(holiday_str))
    
        # Subtract only holidays that fall inside [start, end] AND on Monday..Friday (< 5),
        # because weekend holidays were never included in `business_days` in the first place.
        for holiday in unique_holidays:
            if start <= holiday <= end and holiday.weekday() < 5:
                business_days -= 1
    
        return business_days
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of calendar days like coins packed into identical rolls of 7: no matter which day of the week a roll starts on, 7 consecutive days always contain all seven days of the week once—so 5 weekdays and 2 weekend days. Instead of flipping through a calendar one day at a time across many years, we count how many complete 7-day rolls fit inside the inclusive interval [start, end] (meaning both the start date and the end date are counted), multiply that by 5, inspect at most 6 loose leftover days at the end, and then subtract any distinct weekday holidays that fall inside [start, end].

Why does the naive approach fall short? Walking from start_date to end_date one day at a time takes work proportional to the number of days in the span, so a 100-year range performs over 36,000 steps even when the holiday list is empty. On the other hand, trying to use week math while blindly subtracting len(holidays) produces wrong answers whenever a holiday lands on a Saturday or Sunday, appears twice in holidays, or lies outside [start_date, end_date].

Here is a tiny walkthrough on Example 1 from Thursday 2025-05-01 to Friday 2025-05-09 (9 days total) with holidays = ["2025-05-05", "2025-05-03"]:

1. Total days: (2025-05-09 - 2025-05-01).days + 1 = 9 days
2. Full weeks: 9 // 7 = 1 week (Thu May 1 .. Wed May 7)       -> 1 * 5 = 5 weekdays
3. Leftovers:  9 % 7  = 2 days starting on Thursday           -> Thu, Fri = +2 weekdays (total 7)
4. Holidays:   2025-05-05 is Monday inside the range          -> -1 (total 6)
               2025-05-03 is Saturday (never counted)         -> ignored
Result: 6 business days

Complexity

Let H be the number of strings in holidays and D be the number of calendar days between start_date and end_date.

  • Time: O(H). count_weekdays runs in O(1) constant time—one date subtraction, integer division by 7, and a loop of at most 6 iterations—independent of D. Parsing each holiday string and inserting into the set takes O(1) average time per item across H items, and scanning the set takes O(H) steps.
  • Space: O(H). We store up to H distinct date objects in unique_holidays (O(1) extra space beyond that).

Edge cases

  • start_date after end_date: Treated as an empty date range and returns 0. Because the problem lists this case without prescribing a return value, mention in an interview that raising ValueError or swapping the dates are one-line alternatives depending on the API contract.
  • Single-day range (start_date == end_date): total_days is 1, returning 1 on a non-holiday weekday and 0 on a weekend or weekday holiday.
  • Holidays on Saturday or Sunday: Ignored because holiday.weekday() < 5 is False; count_weekdays never counted them as business days.
  • Duplicate entries in holidays: Collapsed by deduplication (removing repeated values by storing items in a set), so each calendar date is subtracted at most once.
  • Holidays outside [start_date, end_date]: Ignored by the start <= holiday <= end bounds check.
  • Leap years (such as 2024-02-29) and multi-decade spans: Handled automatically by Python's datetime.date proleptic Gregorian calendar arithmetic.

Common mistakes

  • Forgetting + 1 when computing total_days: (end - start).days measures the gap between dates (0 when start == end), so omitting + 1 drops one endpoint of the inclusive range.
  • Subtracting weekend or out-of-range holidays: Subtracting every holiday without checking start <= holiday <= end and holiday.weekday() < 5 undercounts business days and can even produce a negative number.
  • Iterating over holidays directly without a set: If "2025-05-05" appears twice in holidays, looping over the raw list subtracts 2 instead of 1.
  • Assuming leftover days start on Monday: The total_days % 7 leftover days begin 7 * full_weeks days after start, so they start on start.weekday(), not 0 (Monday).
  • Confusing date.weekday() with date.isoweekday(): weekday() numbers Monday..Sunday as 0..6 (weekdays < 5), whereas isoweekday() numbers them 1..7 (weekdays <= 5).

Follow-up questions

  • Suppose a fixed holiday calendar is queried across hundreds of thousands of date intervals—how can you speed up each query? Preprocess holidays once: parse each date, keep only weekday dates (weekday() < 5), deduplicate them, and sort them into an ascending list sorted_holidays in O(H log H) time. Then for each [start, end] query, compute count_weekdays(start, end) in O(1) time and use binary search (repeatedly halving a sorted list to locate a boundary in O(log H) steps, via bisect_right(sorted_holidays, end) - bisect_left(sorted_holidays, start)) to count how many weekday holidays fall in [start, end], bringing each query down from O(H) to O(log H).
  • How would you adapt the implementation for locales whose workweek is not Monday through Friday, such as Sunday through Thursday? Pass a workdays set of weekday integers into the function instead of hard-coding < 5—for example {6, 0, 1, 2, 3} for Sunday through Thursday under Python's Monday = 0 .. Sunday = 6 numbering. Each full week then contributes full_weeks * len(workdays) working days, the leftover loop checks (start_weekday + offset) % 7 in workdays, and the holiday loop checks holiday.weekday() in workdays against that locale's holiday calendar.
  • What extra subtleties arise when inputs arrive as full timestamps with time-zone offsets rather than plain calendar dates? First agree on which region's calendar defines a working day (for example, the customer's local office zone), convert both timestamps into timezone-aware datetimes (timestamps attached to an explicit regional zone such as zoneinfo.ZoneInfo("America/New_York") rather than raw UTC offsets), and extract .date() in that zone. Always convert to local calendar dates before subtracting rather than dividing elapsed seconds by 86,400, because daylight saving time (DST) (seasonal clock shifts that make one local calendar day 23 or 25 hours long) can throw second-based division off by a day; also clarify how partial start/end days (such as starting at 17:30) should be counted.

Follow-up questions

Similar questions

More Airtable interview questions

All 12 Airtable questions →