LinkedIn | Merge Segments

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2019-06-28Added By Anonymous
Source: Link

LinkedInInterview

To improve file transfer speed, a file is split up into different portions and sent from multiple servers. The receiver downloads the file segments and recombine parts into the single file requested. Given the segment class

1class Segment { 2 int start; 3 int end; 4}

implement task class for download manager

1class DownloadTask { 2 // add a segment into recombined file 3 public void add(Segment segment) {} 4 5 // find total length of downloaded segments 6 public int getFileSize() {} 7}

Segments sent from different servers are not fully integrated. As a result segments can be overlapping, like [1, 3] and [2, 4] should be merged and considered as [1, 4] with a total length 3 in getFileSize().


Assume that the file is large and the task streams a lot of segments. Please make sure the add() function is efficient.


Example:

1DownloadTask task = new DownloadTask(); 2task.add([1, 5]); 3task.add([4, 6]); 4task.getFileSize(); // return 5 5task.add([10, 20]); 6task.add([25, 30]); 7task.getFileSize(); // return 20 8task.add([19, 29]); 9task.getFileSize(); // return 25


Comments