Code Logo

Day of the Year

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
"2003-03-01"
Output
60
Explanation

Jan 31 + Feb 28 + Mar 1 = 60 (not leap).

Example 2
Input
"2004-03-01"
Output
61
Explanation

2004 is leap: Jan 31 + Feb 29 + Mar 1 = 61.

Example 3
Input
"2019-02-10"
Output
41
Explanation

Jan 31 + Feb 10 = 41.

Example 4
Input
"2019-01-09"
Output
9
Explanation

Jan 9 is day 9.

Example 5
Input
"2019-12-31"
Output
365
Explanation

Dec 31, not leap = 365.

Algorithm Flow

Recommendation Algorithm Flow for Day of the Year
Recommendation Algorithm Flow for Day of the Year

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.

function solution(date) {
  var days = [31,28,31,30,31,30,31,31,30,31,30,31];
  var parts = date.split('-');
  var y = parseInt(parts[0]), m = parseInt(parts[1]), d = parseInt(parts[2]);
  if (y % 400 === 0 || (y % 4 === 0 && y % 100 !== 0)) days[1] = 29;
  var total = 0;
  for (var i = 0; i < m - 1; i++) total += days[i];
  return total + d;
}

Time O(1), Space O(1).

Best Answers

java
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;
    }
}