Leetcode 1154. Day of the Year

Problem Explanation

In this problem, we are given a string that represents a date in a Gregorian calendar. The date follows the format YYYY-MM-DD. Our task is to return the day number of the year. In other words, we must determine how many days have passed since the beginning of that year up to (and including) the given date.

We will use a simple approach to solve this problem. We first split the string to find out the day, month and year. We calculate the total number of days that have passed in that year by adding up all the days of the completed months and adding the days of the current month. However, as February has different number of days on a leap year, we need to check if the year is a leap year or not.

A year is considered a leap year if:

  • The year is exactly divisible by 4 except for end of century years which must be divisible by 400. This means that the year 2000 was a leap year although 1900 was not.

For example, if the given date is "2003-03-01", we first get the year (2003), month (3) and day (1). Since 2003 is not a leap year, February has 28 days, January has 31 days, and the day of the month is 1. So we just add these up to get 60, the day number for March 1st, 2003.

Python

1
2python
3class Solution:
4    def dayOfYear(self, date: str) -> int:
5        year, month, day = int(date[:4]), int(date[5:7]), int(date[8:10])
6        days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
7        
8        # Check for leap year
9        if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
10            days_in_month[1] = 29
11            
12        return sum(days_in_month[:month-1]) + day

Java

1
2java
3class Solution {
4    public int dayOfYear(String date) {
5        int year = Integer.valueOf(date.substring(0, 4));
6        int month = Integer.valueOf(date.substring(5, 7));
7        int day = Integer.valueOf(date.substring(8, 10));
8        int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
9
10        // Check for leap year
11        if(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)){
12            days[1] = 29;
13        }
14
15        int total = 0;
16        for(int i = 0; i < month-1; i++){
17            total += days[i];
18        }
19        return total + day;
20    }
21}

JavaScript

1
2javascript
3var dayOfYear = function(date) {
4    var year = parseInt(date.substr(0, 4));
5    var month = parseInt(date.substr(5, 2));
6    var day = parseInt(date.substr(8, 2));
7    var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
8    
9    // Check for leap year
10    if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
11        days[1] = 29
12    }
13    
14    return days.slice(0, month - 1).reduce((a, b) => a + b, 0) + day
15};

C++

1
2cpp
3class Solution {
4public:
5  int dayOfYear(string date) {
6    int year = stoi(date.substr(0, 4));
7    int month = stoi(date.substr(5, 2));
8    int day = stoi(date.substr(8));
9    vector<int> days = {31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
10
11    return accumulate(begin(days), begin(days) + month - 1, 0) + day;
12  }
13
14private:
15  bool isLeapYear(int year) {
16    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
17  }
18};

C#

1
2csharp
3public class Solution {
4    public int DayOfYear(string date) {
5        int year = int.Parse(date.Substring(0, 4));
6        int month = int.Parse(date.Substring(5, 2));
7        int day = int.Parse(date.Substring(8, 2));
8        int[] days = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
9
10        // Check for leap year
11        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
12            days[1] = 29;
13        }
14
15        int total = 0;
16        for(int i = 0; i < month - 1; i++){
17            total+=days[i];
18        }
19        return day + total;
20    }
21}

This problem involves basic date calculations depending on whether the year is a leap year or not. The time and space complexity is O(1) since the computation depends on a fixed length string and involves a fixed number of operations.## Ruby

1
2ruby
3class Solution
4    def day_of_year(date)
5        year = date[0..3].to_i
6        month = date[5..6].to_i
7        day = date[8..9].to_i
8        
9        leapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
10        days = [31,28,31,30,31,30,31,31,30,31,30,31]
11        days[1] = 29 if leapYear
12        
13        for i in 0...month-1
14            day += days[i]
15        end
16        return day
17    end
18end

In Ruby, we begin by extracting the year, month, and day from the input string, converting each to an integer in the process. A check is then performed to see if the year is a leap year. If it is, the number of days in February is updated to 29.

An iteration is then conducted over the array of days for each month until the month prior to the current one. The number of days in each month are added to the total day count.

The result is therefore the total number of days that have passed in the year until the input date.

The runtime complexity is constant since the computation only requires a fixed number of operations. The space complexity is also constant as only a fixed amount of space is used, no matter the input size.

Swift

1
2swift
3class Solution {
4    func dayOfYear(_ date: String) -> Int {
5        let year = Int(date.prefix(4))!
6        let month = Int(date[date.index(date.startIndex, offsetBy: 5)..<date.index(date.startIndex, offsetBy: 7)])!
7        let day = Int(date.suffix(2))!
8        
9        let days = [31,(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28,31,30,31,30,31,31,30,31,30,31]
10        return days.prefix(month - 1).reduce(0,+) + day
11    }
12}

In Swift, we start by finding the year, month, and day from string with the String methods prefix(:), suffix(:) and slicing. We go on to check if the current year is a leap year. We have an array of all months' days and if the year is a leap year, we replace February's days with 29.

We reduce the days array up to (but not including) the current month, summing up the days, and add the current day of the month.

With this solution, both time and space complexity are O(1) since the computation involves a fixed number of operations and only uses a fixed amount of memory, regardless of the input.


Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ