Solving Leetcode Interviews in Seconds with AI: Day of the Week
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1185" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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"}. 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 1971 and 2100.
Explanation
Here's a solution to determine the day of the week for a given date, adhering to the constraints and optimizing for efficiency:
- Zeller's Congruence: The core approach leverages Zeller's Congruence, a well-known algorithm to calculate the day of the week. This mathematical formula efficiently computes the day without iterating through dates.
Adjustment for Month: Zeller's Congruence treats January and February as the 13th and 14th months of the previous year. The code includes this adjustment to align with the algorithm's requirements.
Time and Space Complexity: O(1) runtime, O(1) storage
Code
def dayOfTheWeek(day: int, month: int, year: int) -> str:
"""
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"}.
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 1971 and 2100.
"""
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
if month < 3:
month += 12
year -= 1
Y = year % 100
C = year // 100
w = (day + (13 * (month + 1)) // 5 + Y + Y // 4 + C // 4 - 2 * C) % 7
if w < 0:
w += 7
return days[w]