Problem Description
Given a specific date as day, month, and year, determine the day of the week that date falls on. The result must be one of: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", or "Saturday." The input dates are guaranteed to be valid and within the range 1971 to 2100.
Key Insights
- Use a reference date to compute the number of days elapsed until the given date.
- January 1, 1971 is known to be a Friday.
- Account for leap years properly for dates in February.
- After obtaining the total number of days since the reference date, use modulo arithmetic to map the count into a weekday.
Space and Time Complexity
Time Complexity: O(Y) where Y is the number of years between 1971 and the given year (which is bounded by 2100, hence effectively constant). Space Complexity: O(1)
Solution
The approach is to compute the total number of days from January 1, 1971 (a known Friday) to the given date. For each complete year between 1971 and the given year, add 365 days, including an extra day for each leap year. Then, for the current year, add the days for the months before the given month (using 29 days for February in a leap year) and finally add the days within the month (subtracting one to account for the reference day).
Since January 1, 1971 is a Friday, we adjust the total days with an offset so that when the modulo by 7 is taken, it correctly maps to the weekday list ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]. Here, the offset is 5 because (0 days elapsed + 5) mod 7 yields 5, which corresponds to "Friday."
This solution uses simple arithmetic and conditional checks for leap years. It is efficient due to the bounded range of input years.