Problem
Alice and Bob are traveling to Rome for separate business meetings.
You are given 4 strings arriveAlice
, leaveAlice
, arriveBob
, and leaveBob
. Alice will be in the city from the dates arriveAlice
to leaveAlice
(inclusive), while Bob will be in the city from the dates arriveBob
to leaveBob
(inclusive). Each will be a 5-character string in the format "MM-DD"
, corresponding to the month and day of the date.
Return** the total number of days that Alice and Bob are in Rome together.**
You can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
.
Example 1:
Input: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"
Output: 3
Explanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3.
Example 2:
Input: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31"
Output: 0
Explanation: There is no day when Alice and Bob are in Rome together, so we return 0.
Constraints:
All dates are provided in the format
"MM-DD"
.Alice and Bob's arrival dates are earlier than or equal to their leaving dates.
The given dates are valid dates of a non-leap year.
Solution
/**
* @param {string} arriveAlice
* @param {string} leaveAlice
* @param {string} arriveBob
* @param {string} leaveBob
* @return {number}
*/
var countDaysTogether = function(arriveAlice, leaveAlice, arriveBob, leaveBob) {
var daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var aliceDate = [
arriveAlice.split('-').map(item => Number(item)),
leaveAlice.split('-').map(item => Number(item)),
];
var bobDate = [
arriveBob.split('-').map(item => Number(item)),
leaveBob.split('-').map(item => Number(item)),
];
var togetherDate = [
(aliceDate[0][0] * 100 + aliceDate[0][1]) > (bobDate[0][0] * 100 + bobDate[0][1])
? aliceDate[0]
: bobDate[0],
(aliceDate[1][0] * 100 + aliceDate[1][1]) < (bobDate[1][0] * 100 + bobDate[1][1])
? aliceDate[1]
: bobDate[1],
];
if (togetherDate[0][0] === togetherDate[1][0]) {
return Math.max(togetherDate[1][1] - togetherDate[0][1] + 1, 0);
}
if (togetherDate[0][0] > togetherDate[1][0]) {
return 0;
}
return (daysOfMonth[togetherDate[0][0] - 1] - togetherDate[0][1] + 1)
+ Array(togetherDate[1][0] - togetherDate[0][0] - 1).fill(0)
.map((_, i) => daysOfMonth[i + togetherDate[0][0]])
.reduce((sum, i) => sum + i, 0)
+ togetherDate[1][1];
};
Explain:
nope.
Complexity:
- Time complexity : O(1).
- Space complexity : O(1).