Day of the Year - Problem
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
The day number represents which day of the year it is. For example, January 1st is day 1, January 2nd is day 2, and so on.
Note: You need to consider leap years when February has 29 days instead of 28.
Input & Output
Example 1 — Early February
$
Input:
date = "2019-02-10"
›
Output:
41
💡 Note:
January has 31 days, so February 10th is the 31 + 10 = 41st day of the year
Example 2 — Leap Year March
$
Input:
date = "2020-03-01"
›
Output:
61
💡 Note:
2020 is a leap year. January (31) + February (29) + March 1st = 31 + 29 + 1 = 61
Example 3 — Year Start
$
Input:
date = "2021-01-01"
›
Output:
1
💡 Note:
January 1st is always the 1st day of any year
Constraints
- date.length == 10
- date[4] == date[7] == '-'
- All other characters in date are digits
- date represents a calendar date between Jan 1st, 1900 and Dec 31st, 2019
Visualization
Tap to expand
Understanding the Visualization
1
Input
Date string in YYYY-MM-DD format
2
Process
Count days from January 1st to given date
3
Output
Day number (1-366) within the year
Key Takeaway
🎯 Key Insight: Use prefix sums to avoid recalculating cumulative days for each month
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code