Problem Description
Given a string date representing a Gregorian calendar date in the format YYYY-MM-DD, return the day number of the year.
Key Insights
- Parse the input string to extract year, month, and day.
- Determine if the year is a leap year to adjust the number of days in February.
- Use an array (or list) containing the number of days per month for a non-leap year, and update February if necessary.
- Sum the days of the months preceding the given month and add the day to get the final day number.
Space and Time Complexity
Time Complexity: O(1)
Space Complexity: O(1)
Solution
We first split the date string into its year, month, and day components. Based on the year, we check if it is a leap year by using the condition: if the year is divisible by 400 or divisible by 4 but not by 100, then it is a leap year. A list (or array) representing the number of days in each month for a non-leap year is defined, and if the year is a leap year, February's day count is updated to 29. Finally, we compute the day number by summing the days in all preceding months and adding the day of the current month.