File: count-days-spent-together/solution.py

Date: 2026-06-06

Time: 15:56

Purpose

This file solves LeetCode 2409: Count Days Spent Together. It determines how many days two people (Alice and Bob) are simultaneously in Rome, given their arrival and departure dates as "MM-DD" strings within a single non-leap year. The file is self-contained: solution function, helper, and unit tests all in one module.

Key Components

DAYSINMONTH (constant)

A 12-element list of days per month for a non-leap year. Used as a lookup table to convert month-day strings into absolute day-of-year values. The problem guarantees a non-leap year, so February is always 28.

dateto_day(date: str) -> int

Converts a "MM-DD" string to a 1-indexed day-of-year. It slices the string directly (date[:2], date[3:5]) rather than splitting on "-", then sums the days of all preceding months via DAYSINMONTH[:month - 1] and adds the day. For example, "02-05" becomes 31 + 5 = 36.

days_together(...) -> int

The main solver. Converts all four date strings to day-of-year integers, then computes the overlap of two closed intervals [a0, a1] and [b0, b1] using the standard formula:


max(0, min(a1, b1) - max(a0, b0) + 1)

The + 1 accounts for inclusive endpoints (both arrival and departure days count).

TestDaysTogether (unittest.TestCase)

Eight test cases covering: partial overlap, no overlap, identical ranges, single-day overlap, containment, same single day, adjacent-but-disjoint months, and cross-month overlap.

Patterns

Dependencies

Imports: Only unittest from the standard library. No external dependencies.

Imported by: The test_solution.py in the same directory imports from this file. The massive "Imported By" list in the prompt is an artifact of the repo-wide cross-reference — those are other problems' test files, not actual importers of this module.

Flow

1. Caller passes four "MM-DD" strings to days_together.

2. Each string is converted to an integer day-of-year via dateto_day.

3. The overlap of the two date ranges is computed as a single arithmetic expression.

4. Returns 0 if no overlap, otherwise the count of shared days (inclusive).

Invariants

Error Handling

None. The code trusts its inputs per the LeetCode contract. Invalid date strings would propagate a ValueError from int(). There are no try/except blocks or defensive checks.

Topics to Explore

Beliefs