Let's say I have an array of time ranges like so:
[
{ name: 'A', startTime: '10:15', endTime: '11:15'},
{ name: 'B', startTime: '10:45', endTime: '14:15'},
{ name: 'C', startTime: '15:35', endTime: '16:15'},
{ name: 'D', startTime: '11:30', endTime: '16:20'},
{ name: 'E', startTime: '10:30', endTime: '18:00'},
]
which looks like this (visually):
|---A---|________________________________________________________________
_____|------B------|_____________________________________________________
________________________|----C----|______________________________________
___________|-----------D-----------|_____________________________________
___|-------------------E---------------------|___________________________
I wan't to arrange the intervals in a way that will result in an array of arrays
so that:
- Each interval of an array,
does not intersect with ANY other interval in that array
.
(Visual representation of what the end result might look like):
[
[ A, D ],
[ B, C ],
[ E ]
]
- The total number of arrays is absolutely the minimum number possible.
(by that I mean, if an element does intersect with the first array, but not the second array created, don't create a third array put it in the second one)
- Performance is needed (The easiest way would be to iterate through every element to decide if it intersects, but that would be consuming resources like crazy) so something better than O(N^2) would be preferable.
Any ideas? Thank you.