We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Meeting Rooms

Number: 252

Difficulty: Easy

Paid? Yes

Companies: Meta, Amazon, TikTok, Oracle, Apple, Google, eBay, Palo Alto Networks


Problem Description

Given an array of meeting time intervals where each interval is represented as [start, end], determine if a person could attend all meetings without any overlapping intervals.


Key Insights

  • Sort the intervals based on their starting times.
  • Compare each interval's end time with the next interval's start time.
  • Detect overlap if the end time of one meeting exceeds the start time of the following meeting.
  • If no overlaps are detected, all meetings can be attended.

Space and Time Complexity

Time Complexity: O(n log n) due to sorting the intervals.
Space Complexity: O(1) if sorting is done in-place; otherwise O(n).


Solution

The solution starts by sorting the intervals in ascending order by their start times. After sorting, iterate through the intervals and for each consecutive pair, check if the previous meeting's end time exceeds the next meeting's start time. An overlap indicates that the person cannot attend all meetings. The primary data structure used is an array (or list) for holding the intervals. Sorting makes it easier to compare adjacent intervals for potential overlaps.


Code Solutions

# Python solution for checking if one can attend all meetings

def canAttendMeetings(intervals):
    # Sort intervals based on start time
    intervals.sort(key=lambda x: x[0])
    # Iterate through intervals to find any overlap
    for i in range(1, len(intervals)):
        # Check if the previous meeting ends after the current meeting starts
        if intervals[i-1][1] > intervals[i][0]:
            return False
    return True

# Example usage:
print(canAttendMeetings([[0, 30], [5, 10], [15, 20]]))  # Expected output: False
print(canAttendMeetings([[7, 10], [2, 4]]))              # Expected output: True
← Back to All Questions