You are given four dates: arriveAlice
, leaveAlice
, arriveBob
, and leaveBob
. These dates denote the arrival and departure dates of Alice and Bob in MM-DD format. You need to determine how many days Alice and Bob spend together.
Assuming the following based on common constraints in such problems:
Steps:
def countDaysTogether(arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
def dateToDayOfYear(date: str) -> int:
month, day = map(int, date.split('-'))
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return sum(days_in_month[:month-1]) + day
arriveAliceDay = dateToDayOfYear(arriveAlice)
leaveAliceDay = dateToDayOfYear(leaveAlice)
arriveBobDay = dateToDayOfYear(arriveBob)
leaveBobDay = dateToDayOfYear(leaveBob)
startOverlap = max(arriveAliceDay, arriveBobDay)
endOverlap = min(leaveAliceDay, leaveBobDay)
if startOverlap > endOverlap:
return 0
return endOverlap - startOverlap + 1
# Example Usage:
arriveAlice = "08-15"
leaveAlice = "08-18"
arriveBob = "08-16"
leaveBob = "08-19"
print(countDaysTogether(arriveAlice, leaveAlice, arriveBob, leaveBob)) # Output: 3
The solution efficiently calculates the overlapping days using straightforward arithmetic and date conversion, ensuring optimal performance for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?