Dsa
Intervals
Hard
The Intelligent Defragmenter
A storage system contains N files, each occupying a block [S_i, E_i]. You need to group these files into 'clusters'. The clustering algorithm follows two rules:
1. If two files overlap or touch (e.g., [1, 3] and [3, 5]), they MUST be merged into a single continuous block first.
2. Once all overlapping files are merged, two resulting blocks can be part of the same cluster if the gap between them is no more than G units, AND the total span of the cluster (from the start of the first block to the end of the last block) does not exceed L units.
Files are assigned to clusters greedily from left to right. Calculate the total number of clusters formed.
Input Format:
The first line contains N, G, and L.
The next N lines each contain S_i and E_i (files are not necessarily sorted).
Output Format:
A single integer representing the number of clusters.
Example:
Input:
3 2 10
1 3
4 6
8 12
Output:
2
(Explanation: Files [1, 3] and [4, 6] have a gap of 1 (<= G) and a total span of 5 (<= L), so they cluster. File [8, 12] has a gap of 2 (<= G) from the previous block, but adding it would make the span 11 (> L). Thus, [8, 12] starts a new cluster.)
Key concepts
interval-merginggreedy
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now