# Day of the Year Leetcode Solution  Difficulty Level Easy
algorithms coding Interview interviewprep LeetCode LeetCodeSolutions Math

## Problem statement  In the problem ” Day of the Year” we are given a string that contains a date in the format YYYY-MM-DD. Our task is to return the day number of that date.

If the given date is 2020-01-05. This is 5th January 2020 which is the 5th day of the 2020 year. So, we will return 5.

### Example

`date = "2019-01-09"`
`9`

Explanation:

As in the given example, the given day is 9th January 2019. Which is the 9th day of the year 2019. So the answer is 9.

## Approach for Day of the Year Leetcode Solution  As the input is given in the string format we need to extract the date, month, and year from the string in integer data type. So, we will split the string and will extract the date, month, and year from it.

As each month has a different count of the number of days. So to keep track of the number of days for every month we will use one array and will store the number of days for each month.

Now we need to handle the number of days for February month because for leap year it has 29 days and for a non-leap year, it has 28 number of days.

Implementation of Deque using Doubly Linked List

A year is a leap year:

1. if it is divisible by 400
2. it is divisible by 4 but not divisible by 100. To calculate the day of the year simply add all the number of days of each month from January to the given month-1. Add the number of days from the given date. This will give the day of the year for the given date.

### C++ code for Day of the Year

```#include <bits/stdc++.h>
using namespace std;
int dayOfYear(string dt) {
int days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int y = stoi(dt.substr(0, 4)), m = stoi(dt.substr(5, 2)), d = stoi(dt.substr(8));
if (m > 2 && y % 4 == 0 && (y % 100 != 0|| y % 400 == 0)) ++d;
while (--m > 0) d += days[m - 1];
return d;
}
int main()
{
string date="2019-01-09";
int ans=dayOfYear(date);
cout<<ans<<endl;
return 0;
}```
`9`

### Java code for Day of the Year

```import java.util.Arrays;
import java.util.Set ;
import java.util.HashSet;
public class Tutorialcup {
public static int dayOfYear(String S) {
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String[] s = S.split("-");
int y = Integer.parseInt(s);
int m = Integer.parseInt(s);
int d = Integer.parseInt(s);
if (m > 2 && y % 4 == 0 && (y % 100 != 0|| y % 400 == 0)) ++d;
while (--m > 0) d += days[m - 1];
return d;
}
public static void main(String[] args) {
String date="2019-01-09";
int ans=dayOfYear(date);
System.out.println(ans);
}
}```
`9`

## Complexity Analysis of Day of the Year Leetcode Solution  ### Time complexity

The time complexity of the above code is O(1).

### Space complexity

The space complexity of the above code is O(1).

References