# Make given segments non-overlapping by assigning directions

• Last Updated : 30 Jun, 2021

Given an array arr[][] consisting of N segments of the form {L, R, V} where, [L, R] denotes a segment with velocity V in any direction, the task is to check if it is possible to assign directions as left or right to all the segments such that they do not intersect after a long period of time.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[][] = {{5, 7, 2}, {4, 6, 1}, {1, 5, 2}, {6, 5, 1}}
Output: Yes
Explanation: Assign left direction to the first and second segments and right direction to the third and fourth segments.

Input: arr[][] = {{1, 2, 3}}
Output: Yes

Approach: The given problem can be solved based on the following observations:

• Case 1: When the speed of two segments are different:
• The idea is to assign the same direction to both the segments.
• Therefore, after a long period of time, the segments will never intersect or overlap. It is possible that between this time, somewhere the segments overlap. Then, eventually one segment will overtake the other.
• Case 2: When the speed of two segments is the same, but they are not intersecting at t = 0:
• The idea is to assign them the same direction of movement to both segments.
• Since their relative position will not change due to same speed and same direction, after infinite time, their relative positions will remain the same and they won’t overlap.
• Case 3: When the speed of two segments is the same, and they overlap / intersect initially.
• The idea is to assign them the opposite direction of movement.

Below examples illustrate all the above cases:

From the above observations, the idea is to create a Graph for all the overlapping segments and check if the created graph is bipartite or not. If the created graph is bipartite, then it is possible to assign directions to all the segments such that they do not intersect after a long period of time. Therefore, print “Yes”. Otherwise, print “No”
Follow the steps below to solve the problem:

Below is the implementation of above approach:

## Javascript


Output:
Yes

Time Complexity: O(N2)
Auxiliary Space: O(N2)

My Personal Notes arrow_drop_up