LeetCode 2494: Merge Overlapping Events in the Same Hall

Database

Problem Description

Explanation:

Given a list of events in the same hall, where each event is represented by a start time and end time, we need to merge overlapping events to avoid scheduling conflicts. The goal is to merge events that overlap into a single event.

To solve this problem, we can follow these steps:

  1. Sort the events based on their start times.
  2. Initialize an empty list to store the merged events.
  3. Iterate through the sorted events. For each event:
    • If the current event overlaps with the last merged event, update the end time of the last merged event to the maximum of the current event's end time and the last merged event's end time.
    • Otherwise, add the current event to the list of merged events.
  4. Return the list of merged events.

The time complexity of this approach is O(n log n) due to the sorting step, where n is the number of events. The space complexity is O(n) to store the merged events.

:

Solutions

import java.util.*;

class Solution {
    public List<int[]> mergeEvents(int[][] events) {
        Arrays.sort(events, Comparator.comparingInt(a -> a[0]));
        
        List<int[]> mergedEvents = new ArrayList<>();
        for (int[] event : events) {
            if (mergedEvents.isEmpty() || event[0] > mergedEvents.get(mergedEvents.size() - 1)[1]) {
                mergedEvents.add(event);
            } else {
                mergedEvents.get(mergedEvents.size() - 1)[1] = Math.max(mergedEvents.get(mergedEvents.size() - 1)[1], event[1]);
            }
        }
        
        return mergedEvents;
    }
}

Loading editor...