Day of the Year - Problem
Day of the Year is a classic date calculation problem where you need to determine which day of the year a given date represents.

Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, your task is to return the day number of the year.

For example:
• January 1st is day 1
• February 1st is day 32 (31 days in January + 1)
• March 1st is day 60 in a leap year, or 59 in a regular year

The key challenge is handling leap years correctly, where February has 29 days instead of 28.

Input & Output

example_1.py — Basic Date
$ Input: "2019-01-09"
Output: 9
💡 Note: January 9th is simply the 9th day of the year since January is the first month.
example_2.py — Cross Month Boundary
$ Input: "2019-02-10"
Output: 41
💡 Note: February 10th = 31 days in January + 10 days in February = 41st day of the year.
example_3.py — Leap Year
$ Input: "2016-03-01"
Output: 61
💡 Note: March 1st in leap year 2016 = 31 (Jan) + 29 (Feb in leap year) + 1 (Mar 1st) = 61st day.

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
  • The year is between 1900 and 2019

Visualization

Tap to expand
Day of Year CalculatorInput: 2019-02-10Find which day of the year February 10th, 2019 isJanuary31 daysFebruary 1010 daysTotal31 + 10 = 41+=Algorithm Steps:1. days = [31,28,31,30,31,30,31,31,30,31,30,31]2. result = sum(days[0:1]) + 10 = 31 + 10 = 413. February 10, 2019 is the 41st day of the year!
Understanding the Visualization
1
Create Month Lookup
Set up an array with days in each month: [31,28,31,30,31,30,31,31,30,31,30,31]
2
Parse the Date
Extract year, month, and day from the input string
3
Sum Complete Months
Add up all the days in months before the target month
4
Add Current Day
Add the day number within the current month
5
Handle Leap Years
If it's a leap year and we're past February, add one extra day
Key Takeaway
🎯 Key Insight: We only need to sum the days in completed months plus the current day, making this an O(1) operation since there are always exactly 12 months to consider at most.
Asked in
Google 15 Microsoft 12 Amazon 8 Apple 6
42.0K Views
Medium Frequency
~15 min Avg. Time
1.4K 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