Day of the Week Problem
Description
LeetCode Problem 1185.
Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the day, month and year respectively.
Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.
Note: January 1, 1971 was a Friday.
Example 1:
Input: day = 31, month = 8, year = 2019
Output: "Saturday"
Example 2:
Input: day = 18, month = 7, year = 1999
Output: "Sunday"
Example 3:
Input: day = 15, month = 8, year = 1993
Output: "Sunday"
Constraints:
- The given dates are valid dates between the years
1971and2100.
Solution
Approach: Count the Days Since January 1, 1971
We know that January 1, 1971 was a Friday, and the weekdays repeat every 7 days. So if the given date is days days after that Friday, its weekday is entry days % 7 of the list Friday, Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday.
To count days:
- Add 365 or 366 for every full year from 1971 to
year - 1. - Add the lengths of the full months before
monthin the given year, plus one more if the year is a leap year and February is already over (month > 2). - Add
day - 1for the days of the current month before the date.
A year is a leap year when it is divisible by 4, except for years divisible by 100 that are not divisible by 400. In the range 1971 to 2100 this only matters for 2100, which is not a leap year (while 2000 is).
Most languages also have a date library that can answer this directly, but counting the days is short and works the same everywhere.
Complexity: O(1) time and space: at most 130 years and 12 months to add up.
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
names = ["Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"]
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap(y: int) -> bool:
return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
# Days from January 1, 1971 (a Friday) to the given date.
days = day - 1
for y in range(1971, year):
days += 366 if is_leap(y) else 365
for m in range(month - 1):
days += month_days[m]
if month > 2 and is_leap(year):
days += 1 # February 29 of this year has passed
return names[days % 7]