Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Wont the Space Complexity of this solution be O(N+M) which is the worst case?

Avinash Agarwal

Mar 17, 2022

Wont the Space Complexity of this solution be O(N+M) which is the worst case?

0

0

Comments
Comments
Design Gurus
Design Gurus4 years ago

Yes, we will need O(N+M) space for the result list.

R
Richard Yuan4 years ago

Do you guys have an example input that can achieve the worst case space complexity?

Design Gurus
Design Gurus4 years ago

Any two lists where all intervals don't overlap will need O(N+M) space. With such an input, there won't be any merging and all intervals from the input lists will end up in the result list, giving us O(N+M) space complexity.

R
Richard Yuan3 years ago

But shouldn't the result list only contain intervals that intersect? If there is no overlap at all, the resulting list will be empty. The only other possible worst case I could think of is if there is complete overlap between the two input lists which leads to O(n) or O...

Design Gurus
Design Gurus3 years ago

You are right about the interval intersection, our last comment is not valid.

We will have O(M+N) space complexity for input like this:

Input lists: [[0,2],[5,10],[12,23],[24,25]] [[1,5],[8,12],[15,24],[25,26]]

Output: [[1,2],[5,5],[8,10],[12,12],[15,23],[24,24],[25,...

On this page