Count business days excluding holidays
AirtableSoftware Engineer · OnsiteLast updated
This problem tests date manipulation skills and the ability to efficiently calculate working day durations while accounting for dynamic holiday schedules.
Problem Statement
Given a start date, an end date (inclusive), and a list of specific holiday dates, write a function that returns the total number of business days between the two dates. Business days are defined as Monday through Friday. Holidays are specific dates (YYYY-MM-DD strings) that should be excluded even if they fall on a weekday.
Function Signature
def count_business_days(start_date: str, end_date: str, holidays: list[str]) -> int:
pass
Constraints
- Dates are provided in 'YYYY-MM-DD' format.
- The date range can span several years.
holidayslist may contain dates that fall on weekends.
Examples
Example 1:
Input: start_date = "2023-12-25", end_date = "2023-12-29", holidays = ["2023-12-25"]
Output: 4
Explanation: 2023-12-25 is a Monday (holiday), 26-29 are Tuesday-Friday (4 days).
Example 2:
Input: start_date = "2023-01-01", end_date = "2023-01-07", holidays = []
Output: 5
Explanation: Monday (Jan 2) through Friday (Jan 6) are 5 days.
Edge Cases
- Start date is after the end date.
- Start date and end date are the same.
- The range covers multiple weekends and overlapping holidays.
Hints
Hint 1
Consider iterating through every day in the range or calculating the total week-days using math and then subtracting the holiday count.
Hint 2
Convert the input strings to datetime objects to easily extract the day of the week and perform date arithmetic.
Hint 3
Using a set for the holiday list allows for O(1) lookups when checking if a specific day is a holiday.
Follow-up questions
- How would you optimize the solution if you needed to perform this calculation for thousands of different date ranges against the same holiday list?
- What changes are required if the business week definition varies by region (e.g., Sunday to Thursday)?
- How would you handle time zones if the input dates included timestamps instead of just days?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.