Determine if Two Events Have Conflict
Problem
You are given two inclusive events on the same day as event1 = [start1, end1] and event2 = [start2, end2], where each time is a valid 24-hour string HH:MM. A conflict happens when the two events share at least one common moment. Return true if they conflict, otherwise false.
event1 = ["01:00","02:00"], event2 = ["01:20","03:00"]trueevent1 = ["10:00","11:00"], event2 = ["14:00","15:00"]falsedef have_conflict(event1, event2):
def to_min(t):
h, m = t.split(":")
return int(h) * 60 + int(m)
s1, e1 = to_min(event1[0]), to_min(event1[1])
s2, e2 = to_min(event2[0]), to_min(event2[1])
return s1 <= e2 and s2 <= e1
function haveConflict(event1, event2) {
const toMin = (t) => {
const [h, m] = t.split(":");
return Number(h) * 60 + Number(m);
};
const s1 = toMin(event1[0]), e1 = toMin(event1[1]);
const s2 = toMin(event2[0]), e2 = toMin(event2[1]);
return s1 <= e2 && s2 <= e1;
}
boolean haveConflict(String[] event1, String[] event2) {
int s1 = toMin(event1[0]), e1 = toMin(event1[1]);
int s2 = toMin(event2[0]), e2 = toMin(event2[1]);
return s1 <= e2 && s2 <= e1;
}
int toMin(String t) {
String[] p = t.split(":");
return Integer.parseInt(p[0]) * 60 + Integer.parseInt(p[1]);
}
int toMin(string t) {
return stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3, 2));
}
bool haveConflict(vector<string>& event1, vector<string>& event2) {
int s1 = toMin(event1[0]), e1 = toMin(event1[1]);
int s2 = toMin(event2[0]), e2 = toMin(event2[1]);
return s1 <= e2 && s2 <= e1;
}
Explanation
Each event is an inclusive interval on the timeline of a single day. The first job is to make the two events comparable: parse each HH:MM string into a single integer — its minute offset from midnight — with to_min(t) = 60·HH + MM. After that, every time is just a number from 0 to 1439.
Now the question "do the events share a moment?" becomes the classic interval overlap test. Two intervals [s1, e1] and [s2, e2] overlap exactly when each one starts no later than the other one ends: s1 ≤ e2 and s2 ≤ e1.
It is easier to see why by negating it. The events fail to overlap only when one finishes strictly before the other begins — that is, e1 < s2 (event 1 entirely to the left) or e2 < s1 (event 2 entirely to the left). The complement of those two disjoint cases is precisely s1 ≤ e2 and s2 ≤ e1.
Because the events are inclusive, touching endpoints count as a conflict: ["01:15","02:00"] and ["02:00","03:00"] share the single instant 02:00, so the ≤ (not <) is exactly right.
The whole solution is constant work: two string splits, a handful of integer operations, and one boolean — no loops, no sorting.