Day of the Year Problem
Description
LeetCode Problem 1154.
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
Example 1:
Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2:
Input: date = "2019-02-10"
Output: 41
Constraints:
date.length == 10date[4] == date[7] == '-', and all otherdate[i]'s are digitsdaterepresents a calendar date between Jan 1^st, 1900 and Dec 31^st, 2019.
Solution
Approach: Add Up the Earlier Months
The day number is the number of days in all the months before the current one, plus the day of the month. So we split date into year y, month m and day d, and add the lengths of months 1 to m - 1 to d.
The only month whose length changes is February: it has 29 days in a leap year and 28 otherwise. In the Gregorian calendar a year is a leap year when it is divisible by 400, or divisible by 4 but not by 100. The tricky case is a century year: 2000 is a leap year, but 1900 is not, even though both are divisible by 4.
Complexity: O(1) time and space: there are at most 11 months to add.
class Solution:
def dayOfYear(self, date: str) -> int:
y, m, d = (int(part) for part in date.split("-"))
leap = y % 400 == 0 or (y % 4 == 0 and y % 100 != 0)
days = [31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Whole months before this one, plus the days into the current month.
return sum(days[: m - 1]) + d