KatInterview

Working Days Between Two Dates with a Closure List

Math & Bit ManipulationAuto-graded · 18 test cases
MediumAuto-gradedMath & Bit Manipulationdatescalendararithmetic

Last updated

Count Monday-to-Friday days in an inclusive date range, skipping listed closure dates, using week arithmetic instead of day-by-day iteration.

Working Days Between Two Dates

You are given two calendar dates, first_day and last_day, and a list of company closure dates. Return how many working days fall in the range from first_day to last_day, with both endpoints included.

A working day is a date that meets both conditions:

  • It falls on Monday, Tuesday, Wednesday, Thursday, or Friday.
  • It does not appear in the closures list.

Rules

  • All dates are strings in YYYY-MM-DD format.
  • If first_day is later than last_day, the range is empty and the answer is 0.
  • If both dates are the same, the answer is 1 when that day is a working day, and 0 otherwise.
  • A closure date that falls on a Saturday or Sunday has no effect, since weekends are never counted.
  • A closure date outside the range has no effect.
  • If a closure date is listed more than once, it still removes at most one day.

Function

Implement working_days_between(first_day, last_day, closures), which returns an integer.

Constraints

  • Every date is a valid date in YYYY-MM-DD format.
  • The range may span several years, including leap years, so an approach that does not scan every single day is preferable.
  • closures may be empty, may contain duplicates, and may contain weekend dates or dates outside the range.
  • The return value is a non-negative integer.

Examples

Example 1

Input: working_days_between('2023-12-25', '2023-12-29', ['2023-12-25'])

Output: 4

Example 2

Input: working_days_between('2023-01-01', '2023-01-07', [])

Output: 5

Hints

Hint 1

Any 7 consecutive days contain exactly 5 weekdays, no matter which weekday the block starts on. Use this to count whole weeks in one step.

Hint 2

After removing whole weeks, at most 6 days remain. They begin on the same weekday as the first day, so check each of them directly.

Hint 3

Put closures into a set of parsed dates first. Subtract only those inside the range that fall on a weekday, so duplicates, weekend closures and out-of-range closures are handled correctly.