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 other date[i]'s are digitsdate represents a calendar date between Jan 1st, 1900 and Dec 31st, 2019.In #1154 Day of the Year, the input is a date string in the format YYYY-MM-DD. The goal is to determine which day of the year that date represents (from 1 to 365 or 366). The key idea is to parse the year, month, and day from the string and then sum the number of days from all previous months plus the current day.
Maintain an array representing the number of days in each month. While calculating the total, you must also account for leap years, since February has 29 days when the year satisfies leap-year conditions (divisible by 4 but not 100 unless also divisible by 400). After adjusting February if needed, add the days from months before the given month and finally add the day value.
This approach relies on simple string parsing and arithmetic, making it efficient and straightforward. Since the number of months is constant, the computation runs in constant time.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Month days accumulation with leap year check | O(1) | O(1) |
NeetCode
Use these hints if you're stuck. Try solving on your own first.
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
Watch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Problems like Day of the Year may appear in interviews as warm-up or screening questions. They test basic skills such as string parsing, edge case handling, and understanding of date logic like leap years.
A leap year occurs when the year is divisible by 4 but not by 100, unless it is also divisible by 400. If the given year satisfies this condition, February should be treated as having 29 days instead of 28.
The optimal approach is to parse the year, month, and day from the date string and sum the number of days from previous months. You also adjust February if the given year is a leap year. This method runs in constant time because the number of months is fixed.
A simple array or list storing the number of days in each month is sufficient. It allows quick accumulation of days from earlier months and keeps the implementation clean and efficient.