Count Days Without Meetings

Number of days in [1, n] free of any meeting — merge intervals, count gaps.

Medium
Time O(m log m) Space O(1)
LeetCode
4 min read
intervals

Problem#

You’re available days 1..days. Given a list of meeting intervals (1-indexed, inclusive), return the number of days with no meeting.

Examples#

  • days = 10, meetings = [[5,7],[1,3],[9,10]]2 (days 4 and 8)

Constraints#

  • 1 <= days <= 10^9, 1 <= meetings.length <= 10^5.

Approach#

Sort meetings by start, merge them on the fly. Track total busy days; answer is days - busy.

Solution#

Count Days Without Meetings
class Solution {
public:
int countDays(int days, vector<vector<int>>& meetings) {
sort(meetings.begin(), meetings.end());
long long busy = 0;
int curStart = -1, curEnd = -1;
for (auto& m : meetings) {
if (m[0] > curEnd) {
busy += curEnd - curStart + 1;
curStart = m[0];
curEnd = m[1];
} else {
curEnd = max(curEnd, m[1]);
}
}
if (curStart >= 0) busy += curEnd - curStart + 1;
return days - busy;
}
};

Editorial#

Merging-as-we-go and summing the merged lengths avoids materializing the whole merged list. Tracking with a “current” interval plus a deferred commit handles the first iteration cleanly (we only commit when we encounter a non-overlapping next interval). The final commit picks up the last block.

Complexity#

  • Time: O(m log m) for the sort.
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.