File: day-of-the-year/solution.py

Date: 2026-06-06

Time: 16:10

day-of-the-year/solution.py

Purpose

This file solves LeetCode 1154 — Day of the Year: given a date string in YYYY-MM-DD format, return which day of the year it is (1-indexed). It's a self-contained module that bundles the solution, a leap-year helper, and a full test suite in one file — the standard layout across this repo.

Key Components

DAYSINMONTH (line 5) — A 12-element list of day counts for a non-leap year. February is hardcoded to 28; leap-year adjustment is handled separately in the main function rather than mutating this constant.

isleapyear(year: int) -> bool (line 8) — Implements the standard Gregorian leap-year rule: divisible by 4, except centuries unless also divisible by 400. This is extracted as a standalone function rather than inlined, which makes the logic reusable (and it's tested independently in testleapyear).

dayOfYear(date: str) -> int (line 20) — The core solver. Parses the date string, sums the days from all complete months before the target month via DAYSINMONTH[:month - 1], adds the current day, then conditionally adds 1 for leap years when the month is past February.

TestDayOfYear (line 33) — 12 test cases covering boundary conditions: Jan 1, Dec 31 (leap and non-leap), the Feb 28/29/Mar 1 boundary on leap years, and the century rules (1900 is not a leap year, 2000 is).

Patterns

Dependencies

Imports: Only unittest from the standard library. No datetime — the solution does the calendar math manually.

Imported by: The testsolution.py in this directory, plus hundreds of other testsolution.py files across the repo. The "Imported By" list in the prompt is misleading — those files don't actually import *this* solution. They follow the same structural pattern, and the cross-references reflect the repo's test harness wiring, not real import edges.

Flow

1. dayOfYear receives "YYYY-MM-DD".

2. split("-") produces three strings; map(int, ...) converts to (year, month, day).

3. DAYSINMONTH[:month - 1] slices the lookup table to get only the months that have fully passed. sum(...) totals their days.

4. + day adds the current day-of-month.

5. If it's a leap year *and* the month is March or later (month > 2), add 1 for the extra Feb 29.

Invariants

Error Handling

None. Invalid inputs (malformed strings, out-of-range months, non-dates) will raise ValueError from int() or produce silently wrong results. This is intentional for a LeetCode solution where inputs are guaranteed valid.

Topics to Explore

Beliefs