Talentd
FleetCode
Make and follow sheets.Sign in

Day of the Year solution and explanation

EasyMathString5 min read50.3% acceptanceUpdated 9 Apr 2026
1154. Day of the Year (Leetcode Easy)Programming Live with Larry · 7:09 · 946 viewsWatch on YouTube
9 more videos on this problem
  1. 1154. Day of the Year (Leetcode Easy)Programming Live with Larry · 7:09 · 946 views
  2. Vol67 - Leetcode - Problem 1154 - Day of the year - Golang - Phỏng vấn - Thuật toánYuh lập trình viên · 6:27 · 833 views
  3. LeetCode 1154 : Day of the Year || EASY || JAVA || Detailed SolutionCodeGPT · 8:22 · 667 views
  4. 1154. Day of the Year with Python | Leetcode with Python #leetcode #pythontutorial #youtube #technoArsalan Ahmed · 10:14 · 334 views
  5. #LeetCode 1154 | Day of the Year #JavaSleepy Cracker · 3:36 · 232 views
  6. LeetCode Çözümleri - 1154. Day of the YearSoner Gönül · 8:03 · 208 views
  7. LeetCode 1154 Day of the year | Java SolutionCodeCraft by Tejal · 8:29 · 161 views
  8. 米开:LeetCode 1154. Day of the YearM.C米开朗基罗 · 8:21 · 114 views
  9. No Sound Leetcode 1154: Day of the YearExtremeProgrammer · 2:13 · 22 views
  10. LeetCode 1154: Day of the YearAlitaCode · 24:25 · 3 views

The problem

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

Example 1:

Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.

Example 2:

Input: date = "2019-02-10"
Output: 41

Constraints:

  • date.length == 10
  • date[4] == date[7] == '-', and all other date[i]'s are digits
  • date represents a calendar date between Jan 1st, 1900 and Dec 31st, 2019.

Approach overview

Problem Overview: You receive a date string in the format YYYY-MM-DD. The task is to return which day of the year that date represents. For example, 2019-02-10 corresponds to day 41. The main challenge is correctly handling month lengths and leap years.

Approach 1: Using Predefined Days in Months (O(1) time, O(1) space)

This approach manually calculates the day number by summing the number of days in all months before the given month, then adding the current day. Start by parsing the input string to extract year, month, and day. Maintain an array like [31,28,31,30,31,30,31,31,30,31,30,31] representing days in each month. If the year is a leap year (divisible by 400, or divisible by 4 but not 100), update February to 29 days. Iterate through months before the current month and accumulate their days, then add the given day. The algorithm performs a small fixed loop of at most 12 iterations, so the time complexity is effectively O(1) with O(1) extra space.

This method relies on basic math logic for leap year detection and simple parsing using string operations. Because it avoids heavy libraries and clearly demonstrates the leap year rule, it is the most common implementation used in interviews.

Approach 2: Using Date Libraries for Direct Calculation (O(1) time, O(1) space)

Many languages provide built-in date libraries that already handle calendar calculations. Instead of manually counting days, convert the input string into a date object and compute the difference between that date and the first day of the same year (YYYY-01-01). The difference in days plus one gives the day-of-year value. In JavaScript, for example, you can construct Date objects and subtract timestamps to obtain the day count.

This approach delegates leap year handling, month lengths, and calendar rules to the standard library. It keeps the implementation short and reduces the chance of logical errors. The complexity remains O(1) because all operations are constant-time calculations performed by the library.

Recommended for interviews: The predefined-days approach is typically expected. It shows that you understand leap year rules and can implement simple calendar math without relying on built-in utilities. The date-library solution is perfectly valid in production code, but interviewers often prefer seeing the manual calculation because it demonstrates reasoning with arrays, conditions, and basic math logic.

Approach 1: Using Predefined Days in Months

This approach involves creating a static list of the total days for each month. Parse the given date to extract the year, month, and day. Check if the year is a leap year to adjust February's days if necessary. Sum the days from previous months and add the current month's day to find the day of the year.

from datetime import datetime

def day_of_year(date):
    dt = datetime.strptime(date, "%Y-%m-%d")
    return dt.timetuple().tm_yday

if __name__ == "__main__":
    print(day_of_year("2019-02-10"))  # Output: 41
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DayOfYearCalculator {
    public static int dayOfYear(String date) {
        LocalDate parsedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return parsedDate.getDayOfYear();
    }

    public static void main(String[] args) {
        System.out.println(dayOfYear("2019-02-10"));  // Output: 41
    }
}
#include <iostream>
#include <sstream>
#include <array>

bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int dayOfYear(const std::string& date) {
    int year, month, day;
    std::istringstream(date) >> year;
    date[7] = ' ';
    std::istringstream(date.substr(5)) >> month >> day;

    std::array<int, 13> daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    if (isLeapYear(year)) {
        daysInMonth[2] = 29;
    }

    int dayOfYear = day;
    for (int i = 1; i < month; ++i) {
        dayOfYear += daysInMonth[i];
    }

    return dayOfYear;
}

int main() {
    std::cout << dayOfYear("2019-02-10") << std::endl;  // Output: 41
    return 0;
}
function dayOfYear(date) {
    const parsedDate = new Date(date);
    const startOfYear = new Date(parsedDate.getFullYear(), 0, 0);
    const diff = parsedDate - startOfYear;
    const oneDay = 1000 * 60 * 60 * 24;
    return Math.floor(diff / oneDay);
}

console.log(dayOfYear("2019-02-10"));  // Output: 41
#include <stdio.h>
#include <stdbool.h>

bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int dayOfYear(char *date) {
    int year, month, day;
    sscanf(date, "%d-%d-%d", &year, &month, &day);

    int dayOfMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    if (isLeapYear(year)) {
        dayOfMonth[2] = 29;
    }

    int dayOfYear = day;
    for (int i = 1; i < month; i++) {
        dayOfYear += dayOfMonth[i];
    }

    return dayOfYear;
}

int main() {
    printf("%d\n", dayOfYear("2019-02-10"));  // Output: 41
    return 0;
}
using System;

class DayOfYearCalculator {
    public static int DayOfYear(string date) {
        DateTime parsedDate = DateTime.ParseExact(date, "yyyy-MM-dd", null);
        return parsedDate.DayOfYear;
    }

    static void Main() {
        Console.WriteLine(DayOfYear("2019-02-10"));  // Output: 41
    }
}

This Python solution leverages the datetime module to parse the date string and obtain the day number using the timetuple() method.

Complexity

Time Complexity: O(1), due to library internals.
Space Complexity: O(1), as only a single date object is stored.

Try this approach in the editor

Approach 2: Using Date Libraries for Direct Calculation

This approach utilizes built-in or third-party date libraries (where applicable) to parse the input string and directly acquire the day of the year. This reduces manual effort by leveraging efficient, existing functions.

function dayOfYear(date) {
    const parsedDate = new Date(date + 'T00:00:00');
    return Math.ceil((parsedDate - new Date(parsedDate.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));
}

console.log(dayOfYear("2019-02-10"));  // Output: 41

The code snippet uses JavaScript Date to parse and compute the day of the year by calculating the difference in days from the start of the year.

Complexity

Time Complexity: O(1).
Space Complexity: O(1).

Try this approach in the editor

Approach 3: Direct Calculation

According to the problem, the given date is in the Gregorian calendar, so we can directly calculate which day of the year it is.

First, calculate the year, month, and day from the given date, denoted as y, m, d.

Then, calculate the number of days in February of that year according to the leap year rules of the Gregorian calendar. There are 29 days in February of a leap year and 28 days in a non-leap year.

The leap year calculation rule is: the year can be divided by 400, or the year can be divided by 4 but not by 100.

Finally, calculate which day of the year it is according to the given date, that is, add up the number of days in each previous month, and then add the number of days in the current month.

The time complexity is O(1), and the space complexity is O(1).

function dayOfYear(date: string): number {
    const y = +date.slice(0, 4);
    const m = +date.slice(5, 7);
    const d = +date.slice(8);
    const v = y % 400 == 0 || (y % 4 == 0 && y % 100) ? 29 : 28;
    const days = [31, v, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return days.slice(0, m - 1).reduce((a, b) => a + b, d);
}
func dayOfYear(date string) (ans int) {
	var y, m, d int
	fmt.Sscanf(date, "%d-%d-%d", &y, &m, &d)
	days := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
	if y%400 == 0 || (y%4 == 0 && y%100 != 0) {
		days[1] = 29
	}
	ans += d
	for _, v := range days[:m-1] {
		ans += v
	}
	return
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Using Predefined Days in Months

Time Complexity: O(1), due to library internals.
Space Complexity: O(1), as only a single date object is stored.

Using Date Libraries for Direct Calculation

Time Complexity: O(1).
Space Complexity: O(1).

Direct Calculation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Using Predefined Days in MonthsO(1)O(1)Best for interviews when implementing leap year logic manually
Using Date LibrariesO(1)O(1)Useful in production code where built-in date utilities are available

Frequently asked questions

Is Day of the Year easy or hard?

Day of the Year is classified as an Easy problem. The main concepts are string parsing, simple arithmetic, and applying the leap year rule correctly.

How to solve Day of the Year in O(1)?

Extract the year, month, and day from the YYYY-MM-DD string. Use a fixed array of month lengths, adjust February to 29 if the year is a leap year, sum the days of months before the given month, and add the day value. Since the loop iterates over at most 12 months, the runtime is constant.

What is the best approach for Day of the Year?

The predefined days-per-month approach is the most common solution. Parse the date, sum the days from previous months, adjust February for leap years, and add the current day. This runs in O(1) time and O(1) space because the number of months is fixed.

What data structure is used in Day of the Year?

Most solutions use a small array (or list) storing the number of days in each month. The algorithm also relies on basic string parsing and conditional logic for leap year detection.

What is the time complexity of Day of the Year?

The standard solution runs in O(1) time and O(1) space. At most 12 months are processed when summing days, which is a constant bound independent of input size.

Day of the Year Python or Java solution approach?

In Python or Java, split the date string to extract year, month, and day, store month lengths in an array, adjust February for leap years, and sum previous months. The implementation is short and runs in constant time.

Is Day of the Year asked at Google, Amazon, or Meta?

Problems involving date parsing, leap year rules, and simple calendar calculations appear in coding interviews across companies like Amazon and Google. While this exact question may not always appear, similar math and string manipulation problems are common.

Comments

Now write it yourselfClose this page and solve Day of the Year in the editor, without looking.
Practise Day of the Year