#1154
Day of the Year
EasyMathStringArrayMathematical calculations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal approach efficiently calculates the day of the year by leveraging pre-defined arrays for month days and a simple leap year check, allowing us to compute the result in constant time.
⚙️
Algorithm
4 steps- 1Step 1: Parse the input date string to extract the year, month, and day.
- 2Step 2: Create an array that holds the number of days in each month for a non-leap year.
- 3Step 3: Check if the year is a leap year and adjust February's days if necessary.
- 4Step 4: Use a single loop or direct indexing to sum the days of the months preceding the given month and add the day of the current month.
solution.py9 lines
1# Full working Python code
2
3def day_of_year(date: str) -> int:
4 year, month, day = map(int, date.split('-'))
5 days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
6 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
7 days_in_month[1] = 29
8 return sum(days_in_month[:month-1]) + day
9ℹ
Complexity note: The complexity is O(1) because the operations performed do not depend on the size of the input; they are constant-time operations based on fixed arrays.
- 1Understanding leap years is crucial for accurate date calculations.
- 2Using pre-defined arrays for month days allows for efficient summation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.