Number of Days Between Two Dates - Maths - Easy - LeetCode
💻 coding

Number of Days Between Two Dates - Maths - Easy - LeetCode

1 min read 194 words
1 min read
ShareWhatsAppPost on X
  • 1The program calculates the number of days between two valid dates formatted as YYYY-MM-DD.
  • 2It uses a method to count days since 1971, accounting for leap years.
  • 3The solution has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The program calculates the number of days between two valid dates formatted as YYYY-MM-DD."

Number of Days Between Two Dates - Maths - Easy - LeetCode

Write a program to count the number of days between two dates.

The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

Example 1:

Input: date1 = "2019-06-29", date2 = "2019-06-30" Output: 1 Example 2:

Input: date1 = "2020-01-15", date2 = "2019-12-31" Output: 15

Constraints:

The given dates are valid dates between the years 1971 and 2100.

public class Solution {
 public int DaysBetweenDates(string date1, string date2) {
 return Math.Abs(countSince1971(date1) - countSince1971(date2));
 }
 
 public int countSince1971(String date) {
 var monthDays = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 var data = date.Split('-');
 
 int year = int.Parse(data[0]);
 int month = int.Parse(data[1]);
 int day = int.Parse(data[2]);
 
 for (int i = 1971; i < year; i++) {
 day += isALeapYear(i) ? 366 : 365;
 }
 for (int i = 1; i < month; i++) {
 if (isALeapYear(year) && i == 2) {
 day += 1;
 } 
 day += monthDays[i];
 }
 return day;
 }

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

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 18 October 2020 · 1 min read · 194 words

Part of AskGif Blog · coding

You might also like