![]() |
VOOZH | about |
Given N segments (or ranges) represented by two non-negative integers L and R. Divide these segments into two non-empty groups such that there are no two segments from different groups that share a common point. If it is possible to do so, assign each segment a number from the set {1, 2} otherwise print Not Possible.
Examples:
Input: arr[][] = {{5, 5}, {2, 3}, {3, 4}}
Output: 2 1 1
Since 2nd and 3rd segment have one point common i.e. 3, they should be contained in same group.Input: arr[][] = {{3, 5}, {2, 3}, {1, 4}}
Output: Not Possible
All segments should be contained in the same group since every pair has a common point with each other. Since the other group is empty, answer is not possible.
Prerequisites: Merge Overlapping Intervals
Approach:
Using the concept of merging overlapping intervals, we can assign the same group to all those segments that are overlapping and alternatively changing the group number.
To merge overlapping segments, sort all the segments with respect to their increasing left values, if left values are equal, sort it on the basis of right values first keeping order of the original indices of the segments. Then, iterate over the segments and check if any of the previous segments is overlapping with the current segment. If it does then merge it making it one segment and if it doesn't create a new one
At last, check if one of the group is empty of not. If one of them is empty, answer is not possible, otherwise print all the assigned values of segments.
Algorithm:
Below is the implementation of the above approach:
1 1 1 2
Complexity Analysis: