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:
- It falls on Monday, Tuesday, Wednesday, Thursday, or Friday (Saturdays and Sundays never count).
- 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_dateandend_dateare included in the interval whenstart_date <= end_date(whenstart_date == end_date, the interval covers that single calendar day). - When
start_datecomes chronologically afterend_date, the interval is empty and the function must return0. - Entries in
holidaysmay 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 by1, 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, andholidaysare valid Gregorian calendar dates formatted as'YYYY-MM-DD'. - The span between
start_dateandend_datecan cover decades or centuries, including leap years. 0 <= len(holidays) <= 10^5.
Step-by-step walkthrough
Restate the problem and edge-case rules
We are given two
'YYYY-MM-DD'date strings (start_dateandend_date) and a list of'YYYY-MM-DD'holiday strings. We need to count how many calendar datesdin the inclusive rangestart_date <= d <= end_datesatisfy both rules:dfalls on Monday through Friday (not Saturday or Sunday).dis not listed inholidays.
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:
holidaysmay 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_dateas an edge case without specifying a return value; treating an inverted range as empty and returning0is the standard convention.
Brute force: step through one day at a time
Python's
datetime.datetype handles leap years and month lengths automatically. Callingdate.fromisoformat("2025-05-01")builds adateobject, and calling.weekday()returns an integer from0(Monday) through6(Sunday), so weekdays are simply.weekday() < 5.The most direct solution puts all holiday dates into a set and walks from
starttoendone 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_daysIf the range spans
Ddays andholidayshasHentries, this takesO(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 whenholidaysis empty. We can compute the weekday count inO(1)time regardless of how many years separatestartandend.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_daysis the inclusive number of days fromstarttoend:full_weeks = total_days // 7complete blocks givefull_weeks * 5weekdays 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_weeksdays afterstart—an exact multiple of 7 days later—the first leftover day has the exact same weekday asstart: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 dayoffset(foroffset = 0, 1, ..., leftover_days - 1) has weekday(start_weekday + offset) % 7. The% 7wraps Sunday (6) cleanly back around to Monday (0).Count weekdays in O(1) time
Subtracting two Python
dateobjects gives atimedeltawhose.daysattribute is the gap between them. For example,(date(2025, 5, 1) - date(2025, 5, 1)).daysis0, so we add1to 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_countBecause
leftover_daysis strictly less than7, theforloop runs at most 6 times—even for a 1,000-year range.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 by1if and only if:- We have not already subtracted that same date (handled by storing parsed
dateobjects in aset), - It falls inside the window (
start <= holiday <= end), and - It falls on Monday through Friday (
holiday.weekday() < 5), meaningcount_weekdaysactually 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- We have not already subtracted that same date (handled by storing parsed
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 -> ignoredExample 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 = 10Both traces match the expected outputs
6and10.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_weekdaysruns inO(1)constant time—one date subtraction, integer division by7, and a loop of at most6iterations—independent ofD. Parsing each holiday string and inserting into the set takesO(1)average time per item acrossHitems, and scanning the set takesO(H)steps. - Space:
O(H). We store up toHdistinctdateobjects inunique_holidays(O(1)extra space beyond that).
Edge cases
start_dateafterend_date: Treated as an empty date range and returns0. Because the problem lists this case without prescribing a return value, mention in an interview that raisingValueErroror swapping the dates are one-line alternatives depending on the API contract.- Single-day range (
start_date == end_date):total_daysis1, returning1on a non-holiday weekday and0on a weekend or weekday holiday. - Holidays on Saturday or Sunday: Ignored because
holiday.weekday() < 5isFalse;count_weekdaysnever counted them as business days. - Duplicate entries in
holidays: Collapsed by deduplication (removing repeated values by storing items in aset), so each calendar date is subtracted at most once. - Holidays outside
[start_date, end_date]: Ignored by thestart <= holiday <= endbounds check. - Leap years (such as
2024-02-29) and multi-decade spans: Handled automatically by Python'sdatetime.dateproleptic Gregorian calendar arithmetic.
Common mistakes
- Forgetting
+ 1when computingtotal_days:(end - start).daysmeasures the gap between dates (0whenstart == end), so omitting+ 1drops one endpoint of the inclusive range. - Subtracting weekend or out-of-range holidays: Subtracting every holiday without checking
start <= holiday <= end and holiday.weekday() < 5undercounts business days and can even produce a negative number. - Iterating over
holidaysdirectly without aset: If"2025-05-05"appears twice inholidays, looping over the raw list subtracts2instead of1. - Assuming leftover days start on Monday: The
total_days % 7leftover days begin7 * full_weeksdays afterstart, so they start onstart.weekday(), not0(Monday). - Confusing
date.weekday()withdate.isoweekday():weekday()numbers Monday..Sunday as0..6(weekdays< 5), whereasisoweekday()numbers them1..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
holidaysonce: parse each date, keep only weekday dates (weekday() < 5), deduplicate them, and sort them into an ascending listsorted_holidaysinO(H log H)time. Then for each[start, end]query, computecount_weekdays(start, end)inO(1)time and use binary search (repeatedly halving a sorted list to locate a boundary inO(log H)steps, viabisect_right(sorted_holidays, end) - bisect_left(sorted_holidays, start)) to count how many weekday holidays fall in[start, end], bringing each query down fromO(H)toO(log H). - How would you adapt the implementation for locales whose workweek is not Monday through Friday, such as Sunday through Thursday? Pass a
workdaysset of weekday integers into the function instead of hard-coding< 5—for example{6, 0, 1, 2, 3}for Sunday through Thursday under Python'sMonday = 0 .. Sunday = 6numbering. Each full week then contributesfull_weeks * len(workdays)working days, the leftover loop checks(start_weekday + offset) % 7 in workdays, and the holiday loop checksholiday.weekday() in workdaysagainst 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 by86,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 at17:30) should be counted.
Follow-up questions
- Suppose a fixed holiday calendar is queried across hundreds of thousands of date intervals—how can you speed up each query?
- How would you adapt the implementation for locales whose workweek is not Monday through Friday, such as Sunday through Thursday?
- What extra subtleties arise when inputs arrive as full timestamps with time-zone offsets rather than plain calendar dates?
Similar questions
- Breadth-First Object Graph Serialization
- Thread-Safe On-Demand Connection Pool
- Sharded Multi-Tenant Full-Text Search Service
- Idempotent Asynchronous Job Execution API
- Command-Pattern Undo and Redo Engine for Spreadsheets
- Deterministic JSON Wire Format for Cyclic Graphs
More Airtable interview questions
- Command-Pattern Undo and Redo Engine for Spreadsheets Medium
- Fast Best-Fit Dispatcher for Memory-Bound Workloads Easy
- Deterministic JSON Wire Format for Cyclic Graphs Hard Pro
- Schema-Grounded Formula Assistant for Collaborative Tables Medium Pro
- Thread-Safe On-Demand Connection Pool Medium Pro
- Sharded Multi-Tenant Full-Text Search Service Medium Pro
- Idempotent Asynchronous Job Execution API Medium Pro
- Workspace Metric Drop Triage and Recommendation Experiment Easy Pro
- Resilient HTTP Client with Retries and Idempotency Medium Pro
- Breadth-First Object Graph Serialization Medium Pro