Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Build confidence with an intuition-first walkthrough focused on math fundamentals.
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:
1971 and 2100.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math
"2019-06-29" "2019-06-30"
"2020-01-15" "2019-12-31"
count-days-spent-together)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1360: Number of Days Between Two Dates
class Solution {
public int daysBetweenDates(String date1, String date2) {
return Math.abs(calcDays(date1) - calcDays(date2));
}
private boolean isLeapYear(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
private int daysInMonth(int year, int month) {
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
days[1] += isLeapYear(year) ? 1 : 0;
return days[month - 1];
}
private int calcDays(String date) {
int year = Integer.parseInt(date.substring(0, 4));
int month = Integer.parseInt(date.substring(5, 7));
int day = Integer.parseInt(date.substring(8));
int days = 0;
for (int y = 1971; y < year; ++y) {
days += isLeapYear(y) ? 366 : 365;
}
for (int m = 1; m < month; ++m) {
days += daysInMonth(year, m);
}
days += day;
return days;
}
}
// Accepted solution for LeetCode #1360: Number of Days Between Two Dates
func daysBetweenDates(date1 string, date2 string) int {
return abs(calcDays(date1) - calcDays(date2))
}
func isLeapYear(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}
func daysInMonth(year, month int) int {
days := [12]int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if isLeapYear(year) {
days[1] = 29
}
return days[month-1]
}
func calcDays(date string) int {
year, _ := strconv.Atoi(date[:4])
month, _ := strconv.Atoi(date[5:7])
day, _ := strconv.Atoi(date[8:])
days := 0
for y := 1971; y < year; y++ {
days += 365
if isLeapYear(y) {
days++
}
}
for m := 1; m < month; m++ {
days += daysInMonth(year, m)
}
days += day
return days
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #1360: Number of Days Between Two Dates
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
def isLeapYear(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def daysInMonth(year: int, month: int) -> int:
days = [
31,
28 + int(isLeapYear(year)),
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
]
return days[month - 1]
def calcDays(date: str) -> int:
year, month, day = map(int, date.split("-"))
days = 0
for y in range(1971, year):
days += 365 + int(isLeapYear(y))
for m in range(1, month):
days += daysInMonth(year, m)
days += day
return days
return abs(calcDays(date1) - calcDays(date2))
// Accepted solution for LeetCode #1360: Number of Days Between Two Dates
struct Solution;
impl Solution {
fn days_between_dates(date1: String, date2: String) -> i32 {
let (y1, m1, d1) = Self::parse(date1);
let (y2, m2, d2) = Self::parse(date2);
let mut s1 = 0;
let mut s2 = 0;
for i in 1971..y1 {
s1 += if Self::is_leap(i) { 366 } else { 365 };
}
for i in 1971..y2 {
s2 += if Self::is_leap(i) { 366 } else { 365 };
}
s1 += Self::day_of_year(y1, m1, d1);
s2 += Self::day_of_year(y2, m2, d2);
(s1 as i32 - s2 as i32).abs()
}
fn parse(date: String) -> (usize, usize, usize) {
let a: Vec<&str> = date.split_terminator('-').collect();
let year = a[0].parse::<usize>().unwrap();
let month = a[1].parse::<usize>().unwrap();
let day = a[2].parse::<usize>().unwrap();
(year, month, day)
}
fn is_leap(year: usize) -> bool {
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
fn day_of_year(year: usize, month: usize, day: usize) -> usize {
let mut days: Vec<usize> = vec![31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let mut sum = 0;
if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
days[1] += 1;
}
for i in 0..month - 1 {
sum += days[i];
}
sum += day;
sum
}
}
#[test]
fn test() {
let date1 = "2019-06-29".to_string();
let date2 = "2019-06-30".to_string();
let res = 1;
assert_eq!(Solution::days_between_dates(date1, date2), res);
let date1 = "2020-01-15".to_string();
let date2 = "2019-12-31".to_string();
let res = 15;
assert_eq!(Solution::days_between_dates(date1, date2), res);
}
// Accepted solution for LeetCode #1360: Number of Days Between Two Dates
function daysBetweenDates(date1: string, date2: string): number {
return Math.abs(calcDays(date1) - calcDays(date2));
}
function isLeapYear(year: number): boolean {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function daysOfMonth(year: number, month: number): number {
const days = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return days[month - 1];
}
function calcDays(date: string): number {
let days = 0;
const [year, month, day] = date.split('-').map(Number);
for (let y = 1971; y < year; ++y) {
days += isLeapYear(y) ? 366 : 365;
}
for (let m = 1; m < month; ++m) {
days += daysOfMonth(year, m);
}
days += day - 1;
return days;
}
Use this to step through a reusable interview workflow for this problem.
Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.
Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.