Python 1154.py
class Solution:
def dayOfYear(self, date: str) -> int:
year, month, day = [ int(s) for s in date.split("-") ]
# leap years
length = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ] # no need for December
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
length[1] = 29
return day + sum(length[i] for i in range(month - 1))
Difficulty
and has an acceptance rate of about 50% (200k+ submissions).
Typical patterns to solve this problem:
- Math
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the ordinal day of a given calendar date expressed as a string in the ISO-8601 format YYYY-MM-DD. It parses the components, determines whether the year is a leap year, adjusts February’s length accordingly, and finally aggregates the days of the preceding months with the day of the month to obtain the result.
Key Steps
Parsing the Input
year, month, day = [int(s) for s in date.split("-")]
The single line splits the input string on the hyphen delimiter, converts each fragment to an integer, and assigns them to year, month, and day. This compact expression eliminates the need for intermediate variables and ensures that the three components are readily available for subsequent calculations.
Determining Leap-Year Status
length = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30] # no need for December
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
length[1] = 29
A static list length holds the day counts for the first eleven months, deliberately omitting December because its length is never required for the cumulative sum. The conditional expression implements the Gregorian leap-year rule: a year divisible by 4 is a leap year unless it is also divisible by 100, except when divisible by 400. When the condition holds, the entry for February (index 1) is updated from 28 to 29.
Accumulating Days
return day + sum(length[i] for i in range(month - 1))
The final expression adds the day of the month to the total number of days contributed by all earlier months. The generator expression iterates over indices 0 through month-2, summing the corresponding month lengths from the length list. The result is the day-of-year value.
Edge Cases Handled
The algorithm correctly processes dates that fall on February 29 in leap years because the leap-year adjustment modifies February’s length before the summation. For non-leap years, February retains its standard 28-day length, ensuring that a date such as 2021-02-28 yields the correct ordinal value. The omission of December from the length list does not affect correctness because the summation only iterates up to month-1; when month equals 12, the range evaluates to 0 … 10, covering all months preceding December. Consequently, dates in December are handled without requiring an explicit entry for the twelfth month.
Performance Optimizations
The implementation avoids constructing auxiliary data structures beyond the fixed length list. By using a generator expression inside sum, it iterates over the required slice of the list without creating an intermediate list, reducing memory overhead. The leap-year check is performed once per invocation, and the conditional update touches only a single element of the length list, keeping the operation constant-time. The overall flow consists of a small number of arithmetic and indexing operations, leading to fast execution for any valid input date.
ELI5 - Simplified Explanation
Imagine that every year is like a big game board made up of many small boxes, and each box represents one day. To figure out which number day it is, the code first looks at the date you give it, like a birthday or a holiday. It breaks the date apart into the year, the month, and the day so it can understand exactly when that time falls.
There is a list that remembers how many days are inside each month, starting from January and going through November. Sometimes, a year has a special extra day in February to keep our calendars perfect, which is called a leap year. The code checks if the year is one of these special ones, and if it is, it adds that extra day to February so the count stays right.
Once the code knows everything about the months, it adds up all the days in the months that came before the one you picked. Finally, it adds the number of days from the current month to that total. This gives you the final number for which day of the year it is, kind of like counting how many squares you have jumped forward on your board game.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | JS | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1185: Day of the Week
- problem 2864: Maximum Odd Binary Number
- problem 1011: Capacity To Ship Packages Within D Days
- problem 1441: Build an Array With Stack Operations
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality