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
Day of the Year - Prefix Sum Approach INPUT Date String: "2019-02-10" Parsed Values: Year 2019 Month 02 Day 10 Days per Month Array: 31 28 31 30 31 30 31 31 30 31 30 31 Jan Feb Mar Apr May Jun Feb has 28 days (non-leap) 2019 is NOT a leap year ALGORITHM STEPS 1 Build Prefix Sum Cumulative days for each month 0 31 59 90 120 151 ... 2 Check Leap Year Divisible by 4, not 100, or 400 2019 % 4 != 0 --> NOT leap 3 Get Days Before Month prefix[month-1] = prefix[1] prefix[1] = 31 days 4 Add Current Day prefix[month-1] + day 31 + 10 = 41 FINAL RESULT Day Calculation Breakdown: January (Complete) 31 days + February (Partial - 10 days) 10 days = Day of Year 41 Output: 41 OK - Feb 10, 2019 is day 41 Key Insight: Prefix sum array stores cumulative days up to each month. To find day of year: result = prefix[month - 1] + day. For leap years (divisible by 4, not 100, or 400), add 1 extra day if month is greater than February. Time: O(1), Space: O(1). TutorialsPoint - Day of the Year | Prefix Sum Array Approach
Asked in
Microsoft 15 Apple 8
24.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen