[Day 6 of 100] Same as yesterday but more complicated

Welt
2 min read2 days ago

--

If you’ve read the day 5 of this series, then today’s exercise is easy for you. Let’s see it.

1. About the problem

Problem

Description: In this problem, we have a calendar and the events in this calendar. Our mission is to allow the inserting of new event such that we prevent the triple booking. A triple booking happens when three events have some non-empty intersection (in other words, when some moment is common to all the three events).
Input: the array of events
Output: the array of bool mentioning either the event can be added or not

2. Solution

public class MyCalendarTwo {
private List<int[]> _books = [];

public bool Book(int start, int end)
{
var intersect = new List<int[]>();
foreach (var book in _books)
{
if (start >= book[1] || book[0] >= end) continue;
var overlap = new[] { Math.Max(start, book[0]), Math.Min(end, book[1]) };
if (intersect.Any(i => overlap[0] < i[1] && i[0] < overlap[1])) return false;
intersect.Add(overlap);
}

_books.Add([start, end]);
return true;
}
}
Result

This exercise is easy and quite similar to yesterday. If you are interested, this is the link. Then that’s it for today. I see ya tomorrow!

--

--