LeetCode 0253. Meeting Rooms II Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0253. Meeting Rooms II

Description

Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.

 

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2

Example 2:

Input: intervals = [[7,10],[2,4]]
Output: 1

 

Constraints:

  • 1 <= intervals.length <= 104
  • 0 <= starti < endi <= 106

Solutions

Solution 1: Difference Array

We can implement this using a difference array.

First, we find the maximum end time of all the meetings, denoted as m. Then, we create a difference array d of length m + 1. For each meeting, we add to the corresponding positions in the difference array: d[l] = d[l] + 1 for the start time, and d[r] = d[r] - 1 for the end time.

Next, we calculate the prefix sum of the difference array and find the maximum value of the prefix sum, which represents the minimum number of meeting rooms required.

The time complexity is O(n + m) and the space complexity is O(m), where n is the number of meetings and m is the maximum end time.

PythonJavaC++GoTypeScriptRust
class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: m = max(e[1] for e in intervals) d = [0] * (m + 1) for l, r in intervals: d[l] += 1 d[r] -= 1 ans = s = 0 for v in d: s += v ans = max(ans, s) return ans(code-box)

Solution 2: Difference (Hash Map)

If the meeting times span a large range, we can use a hash map instead of a difference array.

First, we create a hash map d, where we add to the corresponding positions for each meeting's start time and end time: d[l] = d[l] + 1 for the start time, and d[r] = d[r] - 1 for the end time.

Then, we sort the hash map by its keys, calculate the prefix sum of the hash map, and find the maximum value of the prefix sum, which represents the minimum number of meeting rooms required.

The time complexity is O(n × log n) and the space complexity is O(n), where n is the number of meetings.

PythonJavaC++GoTypeScriptRust
class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: d = defaultdict(int) for l, r in intervals: d[l] += 1 d[r] -= 1 ans = s = 0 for _, v in sorted(d.items()): s += v ans = max(ans, s) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !