Open In App

Find if there exists a direction for ranges such that no two range intersect

Last Updated : 05 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given N ranges [L, R] with velocities vel[]. The task is to assign each range a direction i.e. either left or right. All the ranges will start moving in the assigned direction at time t = 0. Find, if there is an assignment of directions possible given that no two ranges overlap at infinite time.
Examples: 

Input: range[][] = {{1, 2}, {2, 5}, {3, 10}, {4, 4}, {5, 7}}, 
vel[] = {3, 1, 1, 1, 10} 
Output: No 
Intervals {2, 5}, {3, 10} and {4, 4} share a common point 4 
and have the same velocity.
Input: range[][] = {{1, 2}, {2, 5}, {3, 10}, {4, 4}, {5, 7}}, 
vel[] = {3, 1, 11, 1, 10} 
Output: Yes 

Approach:  

  • At infinite time, if there are two ranges with different velocities then they can never overlap irrespective of their directions since range with greater velocity will always be ahead of that with slower velocity.
  • Now, consider ranges with same velocity. If there exist a point lying in at least 3 ranges with same velocity then the assignment of directions is not possible because even if two of these ranges are assigned a different direction but the third range will definitely intersect with the any one of the other ranges with the same direction.
  • So, for all the velocities, find whether there exists at least 3 ranges such that they share a common point, if yes then assignment is not possible. Otherwise it is possible.

Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
#define MAX 100001
using namespace std;
 
// Structure to hold details of
// each interval
typedef struct
{
    int l, r, v;
} interval;
 
// Comparator to sort intervals
// based on velocity
bool cmp(interval a, interval b)
{
    return a.v < b.v;
}
 
// Function that returns true if the
// assignment of directions is possible
bool isPossible(int range[][3], int N)
{
    interval test[N];
    for (int i = 0; i < N; i++) {
        test[i].l = range[i][0];
        test[i].r = range[i][1];
        test[i].v = range[i][2];
    }
 
    // Sort the intervals based on velocity
    sort(test, test + N, cmp);
 
    for (int i = 0; i < N; i++) {
        int count[MAX] = { 0 };
        int current_velocity = test[i].v;
 
        int j = i;
 
        // Test the condition for all intervals
        // with same velocity
        while (j < N && test[j].v == current_velocity) {
            for (int k = test[j].l; k <= test[j].r; k++) {
                count[k]++;
 
                // If for any velocity, 3 or more intervals
                // share a common point return false
                if (count[k] >= 3)
                    return false;
            }
            j++;
        }
 
        i = j - 1;
    }
 
    return true;
}
 
// Driver code
int main()
{
    int range[][3] = { { 1, 2, 3 },
                       { 2, 5, 1 },
                       { 3, 10, 1 },
                       { 4, 4, 1 },
                       { 5, 7, 10 } };
    int n = sizeof(range) / sizeof(range[0]);
 
    if (isPossible(range, n))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
static int MAX = 100001;
 
// Structure to hold details of
// each interval
static class interval
{
    int l, r, v;
}
 
static class Sort implements Comparator<interval>
{
    // Comparator to sort intervals
    // based on velocity
    public int compare(interval a, interval b)
    {
        return (a.v < b.v ? 1 : 0);
    }
}
 
// Function that returns true if the
// assignment of directions is possible
static boolean isPossible(int range[][], int N)
{
    interval test[] = new interval[N];
    for (int i = 0; i < N; i++)
    {
        test[i] = new interval();
        test[i].l = range[i][0];
        test[i].r = range[i][1];
        test[i].v = range[i][2];
    }
 
    // Sort the intervals based on velocity
    Arrays.sort(test, new Sort());
 
    for (int i = 0; i < N; i++)
    {
        int count[] = new int[MAX];
        int current_velocity = test[i].v;
 
        int j = i;
 
        // Test the condition for all intervals
        // with same velocity
        while (j < N && test[j].v == current_velocity)
        {
            for (int k = test[j].l; k <= test[j].r; k++)
            {
                count[k]++;
 
                // If for any velocity, 3 or more intervals
                // share a common point return false
                if (count[k] >= 3)
                    return false;
            }
            j++;
        }
        i = j - 1;
    }
    return true;
}
 
// Driver code
public static void main(String args[])
{
    int range[][] = {{ 1, 2, 3 },
                     { 2, 5, 1 },
                     { 3, 10, 1 },
                     { 4, 4, 1 },
                     { 5, 7, 10 }};
    int n = range.length;
 
    if (isPossible(range, n))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by Arnab Kundu


Python




# Python implementation of the approach
MAX = 100001
 
# Function that returns true if the
# assignment of directions is possible
def isPossible(range, N):
     
    # Structure to hold details of
    # each interval
    test = [[0 for x in range(3)] for x in range(N)]
    for i in range(N):
        test[i][0] = range[i][0]
        test[i][1] = range[i][1]
        test[i][2] = range[i][2]
         
    # Sort the intervals based on velocity
    test.sort(key = lambda x: x[2])
    for i in range(N):
        count = [0] * MAX
        current_velocity = test[i][2]
        j = i
         
        # Test the condition for all intervals
        # with same velocity
        while (j < N and test[j][2] == current_velocity):
            for k in range(test[j][0], test[j][1] + 1):
                count[k] += 1
                 
                # If for any velocity, 3 or more intervals
                # share a common poreturn false
                if (count[k] >= 3):
                    return False
            j += 1
        i = j - 1
     
    return True
     
# Driver code
range = [[1, 2, 3] ,[2, 5, 1] ,[3, 10, 1],
        [4, 4, 1 ],[5, 7, 10 ]]
n = len(range)
if (isPossible(range, n)):
    print("Yes")
else:
    print("No")
     
# This code is contributed by SHUBHAMSINGH10


C#




// C# implementation of the approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG
{
     
// Structure to hold details of
// each interval
public class interval
{
    public int l, r, v;
}
 
     
public class sortHelper : IComparer<interval>
{
   public int Compare(interval a, interval b)
   {
      return (a.v < b.v ? 1 : 0);
   }
}
     
static int MAX = 100001;
 
// Function that returns true if the
// assignment of directions is possible
static bool isPossible(int [,]range, int N)
{
    interval []test = new interval[N];
    for (int i = 0; i < N; i++)
    {
        test[i] = new interval();
        test[i].l = range[i, 0];
        test[i].r = range[i, 1];
        test[i].v = range[i, 2];
    }
 
    // Sort the intervals based on velocity
    Array.Sort(test, new sortHelper());
 
    for (int i = 0; i < N; i++)
    {
        int []count = new int[MAX];
        int current_velocity = test[i].v;
 
        int j = i;
 
        // Test the condition for all intervals
        // with same velocity
        while (j < N && test[j].v == current_velocity)
        {
            for (int k = test[j].l; k <= test[j].r; k++)
            {
                count[k]++;
 
                // If for any velocity, 3 or more intervals
                // share a common point return false
                if (count[k] >= 3)
                    return false;
            }
            j++;
        }
        i = j - 1;
    }
    return true;
}
 
// Driver code
public static void Main(string []args)
{
    int [,]range = {{ 1, 2, 3 },
                     { 2, 5, 1 },
                     { 3, 10, 1 },
                     { 4, 4, 1 },
                     { 5, 7, 10 }};
                      
    int n = range.GetLength(0);
 
    if (isPossible(range, n))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
// Javascript implementation of the approach
let MAX = 100001;
 
// Structure to hold details of
// each interval
class interval
{
    constructor()
    {
        this.l = this.r = this.v = 0;
    }
}
 
// Function that returns true if the
// assignment of directions is possible
function isPossible(range,N)
{
    let test = new Array(N);
    for (let i = 0; i < N; i++)
    {
        test[i] = new interval();
        test[i].l = range[i][0];
        test[i].r = range[i][1];
        test[i].v = range[i][2];
    }
  
    // Sort the intervals based on velocity
    test.sort(function(a,b){return (a.v < b.v ? 1 : 0);});
  
    for (let i = 0; i < N; i++)
    {
        let count = new Array(MAX);
        for(let i=0;i<MAX;i++)
            count[i]=0;
        let current_velocity = test[i].v;
  
        let j = i;
  
        // Test the condition for all intervals
        // with same velocity
        while (j < N && test[j].v == current_velocity)
        {
            for (let k = test[j].l; k <= test[j].r; k++)
            {
                count[k]++;
  
                // If for any velocity, 3 or more intervals
                // share a common point return false
                if (count[k] >= 3)
                    return false;
            }
            j++;
        }
        i = j - 1;
    }
    return true;
}
 
// Driver code
let range=[[ 1, 2, 3 ],
                     [ 2, 5, 1 ],
                     [ 3, 10, 1 ],
                     [ 4, 4, 1 ],
                     [ 5, 7, 10 ]]
let n = range.length;
 
if (isPossible(range, n))
    document.write("Yes<br>");
else
    document.write("No<br>");
 
// This code is contributed by unknown2108
</script>


Output: 

No

 

Time Complexity: O(N2*K) where N is the number of ranges and K is the largest range possible(i.e largest (R-L) value)
Auxiliary Space: O(1).



Similar Reads

Check if there exists two non-intersect ranges
Given two non-negative integers X and Y, the task is to output the two non-intersecting ranges of non-negative integers such that the sum of the starting and ending point of the first range is equal to X and the product of the starting and ending point of the second range is equal Y. If there is no possible answer output -1. If there are multiple p
7 min read
Check if a pair of integers from two ranges exists such that their Bitwise XOR exceeds both the ranges
Given two integers A and B, the task is to check if there exists two integers P and Q over the range [1, A] and [1, B] respectively such that Bitwise XOR of P and Q is greater than A and B. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: X = 2, Y = 2 Output: YesExplanation:By choosing the value of P and Q as 1 and 2 r
9 min read
Choose points from two ranges such that no point lies in both the ranges
Given two segments [L1, R1] and [L2, R2], the task is to choose two elements x and y from both the ranges (one from range one and other from range two) such that no element belongs to both the ranges i.e. x belongs to first range and y belongs to second range. If no such element exists then print -1 instead. Examples: Input: L1 = 1, R1 = 6, L2 = 3,
4 min read
Minimize group such that no two range of same group intersect
Given an array ranges[] of size N (1 ? N ? 105), where ranges[i] = {starti, endi} represents the range between starti to endi (both inclusive). The task is to find the minimum number of groups that are needed such that each interval of ranges[] belongs to exactly one group and no two ranges[i] in the same group will intersect with each other. Note:
8 min read
Check if two circles intersect such that the third circle passes through their points of intersections and centers
Given centres and the radii of three circles A, B, and C in the form of {X, Y, R}, where (X, Y) is the centre of the circle and R is the radius of that circle. The task is to check if any two circles intersect such that the third circle passes through the intersecting points and the centres of the two circles. If found to be true, then print "Yes".
9 min read
Count of ways to select exactly K non-disjoint ranges from given N ranges
Given two arrays L[] and R[] of size N, and an integer K, the task is to find the number of ways to select exact K disjoint ranges formed by taking elements present at the same index from the array L[] and R[]. Examples: Input: N = 7, K = 3, L[] = {1, 3, 4, 6, 1, 5, 8}, R[] = {7, 8, 5, 7, 3, 10, 9}Output: 9Explanation: The possible ways of selectin
10 min read
Maximum length intersection of all K ranges among all given ranges
Given an array arr[] consisting of N ranges of the form [L, R], the task is to select K ranges such that the intersection length of the K ranges is maximum. Examples: Input: arr[] = {{5, 15}, {1, 10}, {14, 50}, {30, 70}, {99, 100}}, K = 2Output: 21Explanation: Selecting ranges (14, 50) and (30, 70) would give the maximum answer. Therefore, the maxi
7 min read
Check whether there exists a triplet (i, j, k) such that arr[i] &lt; arr[k] &lt; arr[j] for i &lt; j &lt; k
Given an array arr[], the task is to check that if there exist a triplet (i, j, k) such that arr[i]&lt;arr[k]&lt;arr[j] and i&lt;j&lt;k then print Yes else print No. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: NoExplanation:There is no such sub-sequence such that arr[i] &lt; arr[k] &lt; arr[j] Input: arr[] = {3, 1, 5, 0, 4}Output: YesExplanatio
11 min read
Check if there exists a pair (a, b) such that for all the N pairs either of the element should be equal to either a or b
Given an array arr[] of N pairs of distinct integers, the task is to check if there exists any pair (X, Y) such that each pair of the array has at least one common element with the pair (X, Y). Examples: Input: arr[] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}Output: YesExplanation:One of the pair that satisfies the condition is (2, 4). Input: arr[] = {{1,
7 min read
Check if there exists some positive integers X and Y such that P^X is equal to Q^Y
Given two integers P and Q, the task is to check whether a pair (P, Q) is equal or not, and a pair is said to be equal if there exist some positive integers X and Y such that PX = QY. Examples: Input: P = 16 , Q = 4Output: Yes?Explanation: Let X = 2 and Y = 4. Thus, PX = 162 = 256 and QY = 44 = 256 . Thus, the pair (16,4) is equal. Input: P = 12 ,
4 min read
Article Tags :
Practice Tags :