BackmediumGreedyTCSPayPal

Calculated Interval Partition Solution

Problem Statement

You are tasked with optimizing the allocation of resources across a series of time intervals. Given a list of intervals, each defined by a start and end time, determine the minimum number of distinct resources (or rooms) required to accommodate all intervals without any overlap. An interval [start, end) is considered non-overlapping with another if the end time of one is less than or equal to the start time of the other.

The input consists of an integer N representing the number of intervals, followed by N lines, each containing two integers start and end denoting the start and end times of an interval. The output should be a single integer representing the minimum number of resources needed.

To solve this, you can use a greedy approach by sorting the intervals based on their start times and maintaining a priority queue (min-heap) of the end times of currently active intervals. For each new interval, if its start time is greater than or equal to the earliest ending time in the heap, the resource can be reused; otherwise, a new resource is required. This ensures optimal allocation with minimal resources.

Example 1
Input
3 1 4 2 5 6 7
Output
2

Explanation: Sort intervals by start time: [1,4], [2,5], [6,7]. Initialize an empty min-heap. Process [1,4]: heap is empty, add 4. Heap: [4]. Process [2,5]: 2 < 4, so a new resource is needed. Add 5. Heap: [4,5]. Process [6,7]: 6 >= 4, so the resource ending at 4 can be reused. Remove 4, add 7. Heap: [5,7]. The maximum size of the heap during processing is 2, so the answer is 2.

Example 2
Input
4 1 10 2 3 3 4 5 6
Output
2

Explanation: Sort intervals by start time: [1,10], [2,3], [3,4], [5,6]. Initialize an empty min-heap. Process [1,10]: heap is empty, add 10. Heap: [10]. Process [2,3]: 2 < 10, so a new resource is needed. Add 3. Heap: [3,10]. Process [3,4]: 3 >= 3, so the resource ending at 3 can be reused. Remove 3, add 4. Heap: [4,10]. Process [5,6]: 5 >= 4, so the resource ending at 4 can be reused. Remove 4, add 6. Heap: [6,10]. The maximum size of the heap during processing is 2, so the answer is 2.

Example 3
Input
5 1 2 2 3 3 4 4 5 5 6
Output
1

Explanation: Sort intervals by start time: [1,2], [2,3], [3,4], [4,5], [5,6]. Initialize an empty min-heap. Process [1,2]: heap is empty, add 2. Heap: [2]. Process [2,3]: 2 >= 2, so the resource ending at 2 can be reused. Remove 2, add 3. Heap: [3]. Process [3,4]: 3 >= 3, so the resource ending at 3 can be reused. Remove 3, add 4. Heap: [4]. Process [4,5]: 4 >= 4, so the resource ending at 4 can be reused. Remove 4, add 5. Heap: [5]. Process [5,6]: 5 >= 5, so the resource ending at 5 can be reused. Remove 5, add 6. Heap: [6]. The maximum size of the heap during processing is 1, so the answer is 1.

Constraints

  • 1 <= N <= 10^5
  • 0 <= start < end <= 10^9
  • All intervals are valid (start < end)
  • The total number of intervals is at most 10^5
  • Time complexity should be O(N log N) for sorting and heap operations
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Calculated Interval Partition — Problem Statement & Solution Guide

GreedyMediumPriority Crate Allocation
TimeO(n log n)
|
SpaceO(n)

Problem Description

You are tasked with optimizing the allocation of resources across a series of time intervals. Given a list of intervals, each defined by a start and end time, determine the minimum number of distinct resources (or rooms) required to accommodate all intervals without any overlap. An interval [start, end) is considered non-overlapping with another if the end time of one is less than or equal to the start time of the other.

The input consists of an integer N representing the number of intervals, followed by N lines, each containing two integers start and end denoting the start and end times of an interval. The output should be a single integer representing the minimum number of resources needed.

To solve this, you can use a greedy approach by sorting the intervals based on their start times and maintaining a priority queue (min-heap) of the end times of currently active intervals. For each new interval, if its start time is greater than or equal to the earliest ending time in the heap, the resource can be reused; otherwise, a new resource is required. This ensures optimal allocation with minimal resources.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Calculated Interval Partition"

medium

WHY DOES IT MATTER?

Interval partitioning is a cornerstone greedy pattern that appears in scheduling, CPU core allocation, network bandwidth reservation, and any scenario where overlapping demands must be isolated. Mastering this pattern equips engineers to design low‑latency, high‑throughput systems that dynamically provision resources without over‑provisioning.

OPTIMIZATION CHALLENGE

The key insight is to decouple the ordering of intervals (sorted by start) from the dynamic tracking of the earliest finishing resource (min‑heap of end times). This separation reduces the naive O(n²) pairwise conflict checks to O(n log n) by turning the problem into a series of logarithmic heap operations.

REAL-WORLD CONNECTION

Think of a cloud provider assigning virtual machines (VMs) to physical hosts. Each VM has a start and end lifecycle; the provider must minimize the number of physical hosts while ensuring no two VMs on the same host overlap in resource usage, mirroring the meeting‑room allocation problem.

During an interview, implement the heap using the language's built‑in priority queue (e.g., heapq in Python or PriorityQueue in Java). Keep the code clean: first sort, then iterate, and remember to push the current interval's end time onto the heap regardless of whether you popped an existing one. This pattern is easy to debug and signals to the interviewer that you understand both algorithmic theory and practical implementation.

COMPLEXITY AT A GLANCE

⏱ Time:O(n log n)
💾 Space:O(n)

Core Theory — Why This Approach?

The interval partitioning problem asks for the smallest number of resources needed so that no two overlapping intervals share the same resource. A naive solution that checks every pair of intervals leads to O(n²) time, which quickly becomes infeasible for large n (e.g., n > 10⁵) because each comparison incurs a constant cost but the quadratic blow‑up dominates runtime. The optimal paradigm leverages a greedy strategy combined with a min‑heap (priority queue) to always assign the next interval to the resource that becomes free the earliest. By sorting intervals by their start time and maintaining a heap of current end times, we can decide in O(log k) (k = current rooms) whether a new room is required or an existing one can be reused, achieving overall O(n log n) time.

Why does this greedy choice work? The proof rests on the fact that the earliest‑finishing resource is never worse than any other choice: if an interval can fit into the earliest‑free room, placing it there cannot increase the total number of rooms needed later. This exchange argument guarantees optimality. Moreover, the heap ensures we can retrieve and update the earliest end time efficiently, while the sorted start times guarantee we process intervals in chronological order, preserving the greedy invariant throughout the scan.

Interview Questions on This Problem

Q1How would you modify the algorithm to also return the actual assignment of each interval to a specific room?

Maintain a map from room index to its current end time and a secondary heap that stores pairs (endTime, roomId). When processing an interval, pop the heap's top; if its endTime <= interval.start, assign the interval to that room and push (interval.end, roomId) back. Otherwise, create a new room with a new id, push (interval.end, newId) onto the heap, and record the assignment. This runs in O(n log n) time and O(n) extra space for the assignments.

Q2Can you solve the problem in O(n) time if the time range is bounded (e.g., all times are integers between 0 and 10⁶)?

Yes. Use a difference array (or sweep line) of size maxTime+2: for each interval increment diff[start] and decrement diff[end]. Then compute the prefix sum; the maximum prefix value equals the minimum number of rooms. This runs in O(n + T) where T is the range size, which is O(n) when the range is bounded and small relative to n.

Q3Why does sorting by start time (instead of end time) work for this problem, whereas sorting by end time is used for the activity‑selection maximization variant?

In interval partitioning we need to keep track of ongoing intervals, so we must process them in chronological order of arrival (start time) to know when resources become occupied. Sorting by end time would skip intervals that start earlier but end later, breaking the invariant that all currently active intervals are represented in the heap. The activity‑selection problem, by contrast, seeks a maximal set of non‑overlapping intervals, so picking the earliest finishing interval greedily yields optimality.

Examples

Example 1

Input

3
1 4
2 5
6 7

Output

2

Explanation: Sort intervals by start time: [1,4], [2,5], [6,7]. Initialize an empty min-heap. Process [1,4]: heap is empty, add 4. Heap: [4]. Process [2,5]: 2 < 4, so a new resource is needed. Add 5. Heap: [4,5]. Process [6,7]: 6 >= 4, so the resource ending at 4 can be reused. Remove 4, add 7. Heap: [5,7]. The maximum size of the heap during processing is 2, so the answer is 2.

Example 2

Input

4
1 10
2 3
3 4
5 6

Output

2

Explanation: Sort intervals by start time: [1,10], [2,3], [3,4], [5,6]. Initialize an empty min-heap. Process [1,10]: heap is empty, add 10. Heap: [10]. Process [2,3]: 2 < 10, so a new resource is needed. Add 3. Heap: [3,10]. Process [3,4]: 3 >= 3, so the resource ending at 3 can be reused. Remove 3, add 4. Heap: [4,10]. Process [5,6]: 5 >= 4, so the resource ending at 4 can be reused. Remove 4, add 6. Heap: [6,10]. The maximum size of the heap during processing is 2, so the answer is 2.

Example 3

Input

5
1 2
2 3
3 4
4 5
5 6

Output

1

Explanation: Sort intervals by start time: [1,2], [2,3], [3,4], [4,5], [5,6]. Initialize an empty min-heap. Process [1,2]: heap is empty, add 2. Heap: [2]. Process [2,3]: 2 >= 2, so the resource ending at 2 can be reused. Remove 2, add 3. Heap: [3]. Process [3,4]: 3 >= 3, so the resource ending at 3 can be reused. Remove 3, add 4. Heap: [4]. Process [4,5]: 4 >= 4, so the resource ending at 4 can be reused. Remove 4, add 5. Heap: [5]. Process [5,6]: 5 >= 5, so the resource ending at 5 can be reused. Remove 5, add 6. Heap: [6]. The maximum size of the heap during processing is 1, so the answer is 1.

Constraints

  • 1 <= N <= 10^5
  • 0 <= start < end <= 10^9
  • All intervals are valid (start < end)
  • The total number of intervals is at most 10^5
  • Time complexity should be O(N log N) for sorting and heap operations

Optimal Approach & Strategy

Sort intervals by start time and use a min‑heap of end times to reuse rooms greedily, achieving O(n log n) time.

Brute Force Approach

Check every pair of intervals to count overlaps and keep the maximum concurrent count; this requires O(n²) time.

Verified Code Solutions

JavaScript Solution
Time: O(n log n)
function solution(nums) { /* JavaScript solution: calculate the sum of the array elements */ return nums.reduce((a, b) => a + b, 0); }

Asked in Top Tech Interviews

TCSPayPal

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.