Leetcode 2446. Determine if Two Events Have Conflict
You are given two events in the form of two pairs of strings: event1
and event2
. Each string represents an event time in the format "HH:MM"
. Your goal is to determine if these two events conflict with each other. Two events conflict if they overlap in time.
For example:
event1 = ["10:00", "11:00"]
event2 = ["10:30", "12:00"]
In this case, the two events have a conflict because they overlap from 10:30 to 11:00.
"HH:MM"
and in 24-hour time format?
event1
always before event2
in the input order?
"HH:MM"
format to total minutes from 00:00
for easy comparison.#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Function to convert "HH:MM" to minutes from "00:00"
int convertToMinutes(const string &time) {
int hours = stoi(time.substr(0, 2));
int minutes = stoi(time.substr(3, 2));
return hours * 60 + minutes;
}
// Function to determine if two events have a conflict
bool haveConflict(vector<string>& event1, vector<string>& event2) {
int start1 = convertToMinutes(event1[0]);
int end1 = convertToMinutes(event1[1]);
int start2 = convertToMinutes(event2[0]);
int end2 = convertToMinutes(event2[1]);
// Check if the events do not overlap
// If one event starts after the other ends, they do not overlap
if (end1 <= start2 || end2 <= start1) {
return false;
}
// They overlap otherwise
return true;
}
int main() {
vector<string> event1 = {"10:00", "11:00"};
vector<string> event2 = {"10:30", "12:00"};
bool conflict = haveConflict(event1, event2);
cout << (conflict ? "Conflict" : "No Conflict") << endl;
return 0;
}
convertToMinutes
function converts a time string in "HH:MM"
format to the total minutes from midnight.haveConflict
function calculates the start and end times of both events in minutes.[start1, end1)
and [start2, end2)
do not overlap. If end1 <= start2
or end2 <= start1
, the events do not overlap. Otherwise, they do.main
to test our solution with sample inputs.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?