Problem 1154

Abstract / Summary

Given a date in year month day format find the day number within the year counting from day one.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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))
10 lines | 398 bytes | submitted November 2, 2023 | GitHub   28% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (200k+ submissions).

Typical patterns to solve this problem:
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.50 | σ = 1.05

Complexity Analysis

Time: constant
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
30 links | 18 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 easy 2 medium
5 solutions   November 2, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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