Day of the Year
Given a string date representing a date in the format YYYY-MM-DD, return the day number of the year. For example, January 1 is day 1, February 1 is day 32, etc. Account for leap years where February has 29 days.
This is a prefix sum DP problem. Store the cumulative days before each month in an array. For a given month, add the cumulative days before it plus the day of the month. Adjust for leap years: if the year is a leap year and the month is after February, add 1.
A leap year is divisible by 400, or divisible by 4 but not by 100. The prefix sum array allows O(1) computation of the day of the year after O(1) storage.
Edge cases include January (no prefix needed), February in leap years, December 31 (day 365 or 366), and the year 1900 (not a leap year).
The day of the year calculation uses a prefix sum of days per month. This is a classic DP pattern where cumulative sums are precomputed and reused for O(1) queries. The leap year adjustment requires a condition on the year, demonstrating how DP state can incorporate conditional logic.
Example Input & Output
Jan 31 + Feb 28 + Mar 1 = 60 (not leap).
2004 is leap: Jan 31 + Feb 29 + Mar 1 = 61.
Jan 31 + Feb 10 = 41.
Jan 9 is day 9.
Dec 31, not leap = 365.
Algorithm Flow

Solution Approach
Build prefix sum of days per month. For given date, add prefix before month plus day. Add 1 for leap year if after Feb.
Time O(1), Space O(1).
Best Answers
class Solution {
public int solution(String date) {
int[] days={31,28,31,30,31,30,31,31,30,31,30,31};
String[] p=date.split("-");
int y=Integer.parseInt(p[0]),m=Integer.parseInt(p[1]),d=Integer.parseInt(p[2]);
if (y%400==0||(y%4==0&&y%100!=0)) days[1]=29;
int t=0;
for (int i=0;i<m-1;i++) t+=days[i];
return t+d;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
