The Wayback Machine - https://web.archive.org/web/20240824043926/https://www.geeksforgeeks.org/check-if-any-two-intervals-overlap-among-a-given-set-of-intervals/
Open In App

Check if any two intervals intersects among a given set of intervals

Last Updated : 14 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An interval is represented as a combination of start time and end time. Given a set of intervals, check if any two intervals intersect. 

Examples: 

Input:  arr[] = {{1, 3}, {5, 7}, {2, 4}, {6, 8}}
Output: true
The intervals {1, 3} and {2, 4} overlap


Input:  arr[] = {{1, 3}, {7, 9}, {4, 6}, {10, 13}}
Output: false
No pair of intervals overlap. 

Expected time complexity is O(nLogn) where n is number of intervals.
We strongly recommend to minimize your browser and try this yourself first.
A Simple Solution is to consider every pair of intervals and check if the pair intersects or not. The time complexity of this solution is O(n2)

Method 1 
A better solution is to Use Sorting. Following is complete algorithm. 
1) Sort all intervals in increasing order of start time. This step takes O(nLogn) time. 
2) In the sorted array, if start time of an interval is less than end of previous interval, then there is an overlap. This step takes O(n) time.
So overall time complexity of the algorithm is O(nLogn) + O(n) which is O(nLogn).

Below is the implementation of above idea.

C++




// A C++ program to check if any two intervals overlap
#include <algorithm>
#include <iostream>
using namespace std;
  
// An interval has start time and end time
struct Interval {
    int start;
    int end;
};
  
// Compares two intervals according to their starting time.
// This is needed for sorting the intervals using library
// function std::sort().
bool compareInterval(Interval i1, Interval i2)
{
    return (i1.start < i2.start) ? true : false;
}
  
// Function to check if any two intervals overlap
bool isIntersect(Interval arr[], int n)
{
    // Sort intervals in increasing order of start time
    sort(arr, arr + n , compareInterval);
  
    // In the sorted array, if start time of an interval
    // is less than end of previous interval, then there
    // is an overlap
    for (int i = 1; i < n; i++)
        if (arr[i - 1].end > arr[i].start)
            return true;
  
    // If we reach here, then no overlap
    return false;
}
  
// Driver program
int main()
{
    Interval arr1[] = { { 1, 3 }, { 7, 9 }, { 4, 6 }, { 10, 13 } };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    isIntersect(arr1, n1) ? cout << "Yes\n" : cout << "No\n";
  
    Interval arr2[] = { { 6, 8 }, { 1, 3 }, { 2, 4 }, { 4, 7 } };
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
    isIntersect(arr2, n2) ? cout << "Yes\n" : cout << "No\n";
  
    return 0;
}


Java




// A Java program to check if any two intervals overlap
import java.io.*;
import java.lang.*;
import java.util.*;
  
class GFG{
  
// An interval has start time and end time
static class Interval
{
    int start;
    int end;
      
    public Interval(int start, int end)
    {
        super();
        this.start = start;
        this.end = end;
    }
};
  
// Function to check if any two intervals overlap
static boolean isIntersect(Interval arr[], int n)
{
  
    // Sort intervals in increasing order of start time
    Arrays.sort(arr, (i1, i2) -> {
        return i1.start - i2.start;
    });
  
    // In the sorted array, if start time of an interval
    // is less than end of previous interval, then there
    // is an overlap
    for(int i = 1; i < n; i++)
        if (arr[i - 1].end > arr[i].start)
            return true;
  
    // If we reach here, then no overlap
    return false;
}
  
// Driver code
public static void main(String[] args)
{
    Interval arr1[] = { new Interval(1, 3),
                        new Interval(7, 9),
                        new Interval(4, 6), 
                        new Interval(10, 13) };
    int n1 = arr1.length;
  
    if (isIntersect(arr1, n1))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
  
    Interval arr2[] = { new Interval(6, 8), 
                        new Interval(1, 3),
                        new Interval(2, 4), 
                        new Interval(4, 7) };
    int n2 = arr2.length;
      
    if (isIntersect(arr2, n2))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
}
}
  
// This code is contributed by Kingash


Python3




# A Python program to check if any two intervals overlap
  
# An interval has start time and end time
class Interval:
    def __init__(self, start, end):
        self.start = start
        self.end = end
  
# Function to check if any two intervals overlap
def isIntersect(arr, n):
    
    # Sort intervals in increasing order of start time
    arr.sort(key=lambda x: x.start)
  
    # In the sorted array, if start time of an interval
    # is less than end of previous interval, then there
    # is an overlap
    for i in range(1, n):
        if (arr[i - 1].end > arr[i].start):
            return True
  
    # If we reach here, then no overlap
    return False
  
# Driver code
arr1 = [Interval(1, 3), Interval(7, 9), Interval(4, 6), Interval(10, 13)]
n1 = len(arr1)
if (isIntersect(arr1, n1)):
    print("Yes")
else:
    print("No")
  
arr2 = [Interval(6, 8), Interval(1, 3), Interval(2, 4), Interval(4, 7)]
n2 = len(arr2)
  
if (isIntersect(arr2, n2)):
    print("Yes")
else:
    print("No")
  
# This code is contributed by Saurabh Jaiswal


C#




using System;
using System.Linq;
  
class GFG {
  // An interval has start time and end time
  class Interval {
    public int start;
    public int end;
  
    public Interval(int start, int end)
    {
      this.start = start;
      this.end = end;
    }
  }
  
  // Function to check if any two intervals overlap
  static bool IsIntersect(Interval[] arr, int n)
  {
    // Sort intervals in increasing order of start time
    Array.Sort(arr, (i1, i2) => i1.start.CompareTo(i2.start));
  
    // In the sorted array, if start time of an interval
    // is less than end of previous interval, then there
    // is an overlap
    for (int i = 1; i < n; i++) {
      if (arr[i - 1].end > arr[i].start) {
        return true;
      }
    }
  
    // If we reach here, then no overlap
    return false;
  }
  
  // Driver Code
  static void Main(string[] args)
  {
    Interval[] arr1
      = { new Interval(1, 3), new Interval(7, 9),
         new Interval(4, 6), new Interval(10, 13) };
    int n1 = arr1.Length;
  
    if (IsIntersect(arr1, n1)) {
      Console.WriteLine("Yes");
    }
    else {
      Console.WriteLine("No");
    }
  
    Interval[] arr2
      = { new Interval(6, 8), new Interval(1, 3),
         new Interval(2, 4), new Interval(4, 7) };
    int n2 = arr2.Length;
  
    if (IsIntersect(arr2, n2)) {
      Console.WriteLine("Yes");
    }
    else {
      Console.WriteLine("No");
    }
  }
}
  
// This code is contributed by phasing17


Javascript




<script>
// A Javascript program to check if any two intervals overlap
  
// An interval has start time and end time
class Interval
{
    constructor(start,end)
    {
        this.start = start;
        this.end = end;
    }
}
  
// Function to check if any two intervals overlap
function isIntersect(arr,n)
{
    // Sort intervals in increasing order of start time
    arr.sort(function(i1, i2){
        return i1.start - i2.start;
    });
   
    // In the sorted array, if start time of an interval
    // is less than end of previous interval, then there
    // is an overlap
    for(let i = 1; i < n; i++)
        if (arr[i - 1].end > arr[i].start)
            return true;
   
    // If we reach here, then no overlap
    return false;
}
  
// Driver code
let arr1=[new Interval(1, 3),
                        new Interval(7, 9),
                        new Interval(4, 6),
                        new Interval(10, 13) ];
let n1 = arr1.length;
if (isIntersect(arr1, n1))
    document.write("Yes<br>");
else
    document.write("No<br>");
  
let arr2 = [ new Interval(6, 8),
new Interval(1, 3),
new Interval(2, 4),
new Interval(4, 7) ];
let n2 = arr2.length;
  
if (isIntersect(arr2, n2))
    document.write("Yes<br>");
else
    document.write("No<br>");
  
// This code is contributed by rag2127
</script>


Output: 

No
Yes

Time Complexity:  O(nlogn)

Auxiliary Space: O(1)

Method 2: This approach is suggested by Anjali Agarwal. Following are the steps:  

1. Find the overall maximum element. Let it be max_ele 
2. Initialize an array of size max_ele with 0. 
3. For every interval [start, end], increment the value at index start, i.e. arr[start]++ and decrement the value at index (end + 1), i.e. arr[end + 1]- -. 
4. Compute the prefix sum of this array (arr[]). 
5. Every index, i of this prefix sum array will tell how many times i has occurred in all the intervals taken together. If this value is greater than 1, then it occurs in 2 or more intervals. 
6. So, simply initialize the result variable as false and while traversing the prefix sum array, change the result variable to true whenever the value at that index is greater than 1.  

Below is the implementation of this (Method 2) approach. 

C++




// A C++ program to check if any two intervals overlap
#include <algorithm>
#include <iostream>
using namespace std;
  
// An interval has start time and end time
struct Interval {
    int start;
    int end;
};
  
// Function to check if any two intervals overlap
bool isIntersect(Interval arr[], int n)
{
  
    int max_ele = 0;
  
    // Find the overall maximum element
    for (int i = 0; i < n; i++) {
        if (max_ele < arr[i].end)
            max_ele = arr[i].end;
    }
  
    // Initialize an array of size max_ele
    int aux[max_ele + 1] = { 0 };
    for (int i = 0; i < n; i++) {
  
        // starting point of the interval
        int x = arr[i].start;
  
        // end point of the interval
        int y = arr[i].end;
        aux[x]++, aux[y + 1]--;
    }
    for (int i = 1; i <= max_ele; i++) {
        // Calculating the prefix Sum
        aux[i] += aux[i - 1];
  
        // Overlap
        if (aux[i] > 1)
            return true;
    }
  
    // If we reach here, then no Overlap
    return false;
}
  
// Driver program
int main()
{
    Interval arr1[] = { { 1, 3 }, { 7, 9 }, { 4, 6 }, { 10, 13 } };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
  
    isIntersect(arr1, n1) ? cout << "Yes\n" : cout << "No\n";
  
    Interval arr2[] = { { 6, 8 }, { 1, 3 }, { 2, 4 }, { 4, 7 } };
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
    isIntersect(arr2, n2) ? cout << "Yes\n" : cout << "No\n";
  
    return 0;
}
// This Code is written by Anjali Agarwal


Java




// A Java program to check if any two intervals overlap 
class GFG
{ 
  
// An interval has start time and end time 
static class Interval 
{ 
    int start; 
    int end;
    public Interval(int start, int end) 
    {
        super();
        this.start = start;
        this.end = end;
    } 
}; 
  
// Function to check if any two intervals overlap 
static boolean isIntersect(Interval arr[], int n) 
{ 
  
    int max_ele = 0; 
  
    // Find the overall maximum element 
    for (int i = 0; i < n; i++)
    { 
        if (max_ele < arr[i].end) 
            max_ele = arr[i].end; 
    } 
  
    // Initialize an array of size max_ele 
    int []aux = new int[max_ele + 1];
    for (int i = 0; i < n; i++) 
    { 
  
        // starting point of the interval 
        int x = arr[i].start; 
  
        // end point of the interval 
        int y = arr[i].end; 
        aux[x]++;
        aux[y ]--; 
    } 
    for (int i = 1; i <= max_ele; i++)
    { 
        // Calculating the prefix Sum 
        aux[i] += aux[i - 1]; 
  
        // Overlap 
        if (aux[i] > 1) 
            return true; 
    } 
  
    // If we reach here, then no Overlap 
    return false; 
} 
  
// Driver program 
public static void main(String[] args) 
{ 
    Interval arr1[] = { new Interval(1, 3), new Interval(7, 9),
                       new Interval(4, 6), new Interval(10, 13) }; 
    int n1 = arr1.length; 
  
    if(isIntersect(arr1, n1))
        System.out.print("Yes\n");
    else
        System.out.print("No\n"); 
  
    Interval arr2[] = { new Interval(6, 8), new Interval(1, 3),
                        new Interval(2, 4), new Interval(4, 7) }; 
    int n2 = arr2.length; 
    if(isIntersect(arr2, n2))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
}
} 
  
// This code is contributed by 29AjayKumar


Python3




# A Python program to check if any two intervals overlap
  
# An interval has start time and end time
class Interval:
    def __init__(self, start, end):
        self.start = start
        self.end = end
  
# Function to check if any two intervals overlap
def is_intersect(arr, n):
    max_ele = 0
  
    # Find the overall maximum element
    for i in range(n):
        if max_ele < arr[i].end:
            max_ele = arr[i].end
  
    # Initialize an array of size max_ele
    aux = [0] * (max_ele + 1)
    for i in range(max_ele + 1):
        aux[i] = 0
    for i in range(n):
        
        # starting point of the interval
        x = arr[i].start
          
        # end point of the interval
        y = arr[i].end
        aux[x] += 1
        aux[y] -= 1
    for i in range(1, max_ele + 1):
        
        # Calculating the prefix Sum
        aux[i] += aux[i - 1]
          
        # Overlap
        if aux[i] > 1:
            return True
            
    # If we reach here, then no Overlap
    return False
  
# Driver program
arr1 = [Interval(1, 3), Interval(7, 9), Interval(4, 6), Interval(10, 13)]
n1 = len(arr1)
if is_intersect(arr1, n1):
    print("Yes")
else:
    print("No")
  
arr2 = [Interval(6, 8), Interval(1, 3), Interval(2, 4), Interval(4, 7)]
n2 = len(arr2)
if is_intersect(arr2, n2):
    print("Yes")
else:
    print("No")
  
      
# this code is contributed by phasing17


C#




// C# program to check if
// any two intervals overlap 
using System;
  
class GFG
{ 
  
// An interval has start time and end time 
class Interval 
{ 
    public int start; 
    public int end;
    public Interval(int start, int end) 
    {
        this.start = start;
        this.end = end;
    } 
}; 
  
// Function to check if
// any two intervals overlap 
static bool isIntersect(Interval []arr, int n) 
{ 
    int max_ele = 0; 
  
    // Find the overall maximum element 
    for (int i = 0; i < n; i++)
    { 
        if (max_ele < arr[i].end) 
            max_ele = arr[i].end; 
    } 
  
    // Initialize an array of size max_ele 
    int []aux = new int[max_ele + 1];
    for (int i = 0; i < n; i++) 
    { 
  
        // starting point of the interval 
        int x = arr[i].start; 
  
        // end point of the interval 
        int y = arr[i].end; 
        aux[x]++;
        aux[y ]--; 
    } 
      
    for (int i = 1; i <= max_ele; i++)
    { 
        // Calculating the prefix Sum 
        aux[i] += aux[i - 1]; 
  
        // Overlap 
        if (aux[i] > 1) 
            return true; 
    } 
  
    // If we reach here, then no Overlap 
    return false; 
} 
  
// Driver Code
public static void Main(String[] args) 
{ 
    Interval []arr1 = { new Interval(1, 3), 
                        new Interval(7, 9),
                        new Interval(4, 6), 
                        new Interval(10, 13) }; 
    int n1 = arr1.Length; 
  
    if(isIntersect(arr1, n1))
        Console.Write("Yes\n");
    else
        Console.Write("No\n"); 
  
    Interval []arr2 = { new Interval(6, 8), 
                        new Interval(1, 3),
                        new Interval(2, 4),
                        new Interval(4, 7) }; 
    int n2 = arr2.Length; 
    if(isIntersect(arr2, n2))
        Console.Write("Yes\n");
    else
        Console.Write("No\n");
}
}
  
// This code is contributed by Rajput-Ji


Javascript




<script>
// A Javascript program to check if any two intervals overlap
  
// An interval has start time and end time
class Interval
{
    constructor(start, end)
    {
        this.start = start;
        this.end = end;
    }
}
  
// Function to check if any two intervals overlap
function isIntersect(arr, n)
{
    let max_ele = 0;
   
    // Find the overall maximum element
    for (let i = 0; i < n; i++)
    {
        if (max_ele < arr[i].end)
            max_ele = arr[i].end;
    }
   
    // Initialize an array of size max_ele
    let aux = new Array(max_ele + 1);
    for(let i=0;i<(max_ele + 1);i++)
    {
        aux[i]=0;
    }
    for (let i = 0; i < n; i++)
    {
   
        // starting point of the interval
        let x = arr[i].start;
   
        // end point of the interval
        let y = arr[i].end;
        aux[x]++;
        aux[y ]--;
    }
    for (let i = 1; i <= max_ele; i++)
    {
        // Calculating the prefix Sum
        aux[i] += aux[i - 1];
   
        // Overlap
        if (aux[i] > 1)
            return true;
    }
   
    // If we reach here, then no Overlap
    return false;
}
  
// Driver program
let arr1 = [new Interval(1, 3), new Interval(7, 9),
                       new Interval(4, 6), new Interval(10, 13)];
let n1 = arr1.length;
if(isIntersect(arr1, n1))
        document.write("Yes<br>");
    else
        document.write("No<br>");
   
    let arr2 = [ new Interval(6, 8), new Interval(1, 3),
                        new Interval(2, 4), new Interval(4, 7) ];
    let n2 = arr2.length;
    if(isIntersect(arr2, n2))
        document.write("Yes<br>");
    else
        document.write("No<br>");
  
// This code is contributed by avanitrachhadiya2155
</script>


Output: 

No
Yes

Time Complexity : O(max_ele + n) 

Auxiliary Space: O(max_ele)

Note: This method is more efficient than Method 1 if there are more number of intervals and at the same time maximum value among all intervals should be low, since time complexity is directly proportional to O(max_ele). 
 



Previous Article
Next Article

Similar Reads

Find Non-overlapping intervals among a given set of intervals
Given N set of time intervals, the task is to find the intervals which don't overlap with the given set of intervals.Examples: Input: interval arr[] = { {1, 3}, {2, 4}, {3, 5}, {7, 9} } Output: [5, 7] Explanation: The only interval which doesn't overlaps with the other intervals is [5, 7].Input: interval arr[] = { {1, 3}, {9, 12}, {2, 4}, {6, 8} }
7 min read
Count intervals that intersects with a given meeting time
Given an array arr[][2] consisting of N pair of strings representing the starting and ending time (in 12 hours format) and a string P which represents the time of the meeting, the task is to find the count of intervals that contains the time P. Examples: Input: P = “12:01:AM”, arr[][2] = {{“12:00:AM”, “11:55:PM”}, {“12:01:AM”, “11:50:AM”}, {“12:30:
9 min read
Maximum sum of at most two non-overlapping intervals in a list of Intervals | Interval Scheduling Problem
Given an array interval of length N, where each element represents three values, i.e. {startTime, endTime, value}. The task is to find the maximum sum of values of at most two non-overlapping intervals. Example: Input: interval[] = [[1, 3, 2], [4, 5, 2], [2, 4, 3]]Output: 4Explanation: Select interval 1 and 2 (as third interval is overlapping). The
7 min read
Check if a line touches or intersects a circle
Given coordinate of the center and radius &gt; 1 of a circle and the equation of a line. The task is to check if the given line collides with the circle or not. There are three possibilities : Line intersects the circle.Line touches the circle.Line is outside the circle Note: General equation of a line is a*x + b*y + c = 0, so only constant a, b, c
6 min read
Minimize segments required to be removed such that at least one segment intersects with all remaining segments
Given an array arr[] consisting of N pairs [L, R], where L and R denotes the start and end indices of a segment, the task is to find the minimum number of segments that must be deleted from the array such that the remaining array contains at least one segment which intersects with all other segments present in the array. Examples: Input: arr[] = {{
10 min read
Probability of getting two consecutive heads after choosing a random coin among two different types of coins
Given two coins which have probability of getting heads p% and q% respectively, the task is to determine the probability of getting two consecutive heads after choosing random coins among the given coins.Examples: Input: p = 33, q = 66 Output: 0.550000000000000Input: p = 33, q = 66 Output: 0.550000000000000 Approach: Since both the coins are not id
5 min read
Check if two strings can be made equal by swapping one character among each other
Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples: Input: A = "SEEKSFORGEEKS", B = "GEEKSFORGEEKG" Output: Yes "SEEKSFORGEEKS" and "GEEKSFORGEEKG" After removing the elements which are the same and have the same index
10 min read
Find intersection of intervals given by two lists
Given two 2-D arrays which represent intervals. Each 2-D array represents a list of intervals. Each list of intervals is disjoint and sorted in increasing order. Find the intersection or set of ranges that are common to both the lists. Disjoint means no element is common in a list. Example: {1, 4} and {5, 6} are disjoint while {1, 4} and {2, 5} are
7 min read
Check if given intervals can be made non-overlapping by adding/subtracting some X
Given an array arr[] containing N intervals, the task is to check that if the intervals can be added or subtracted by X after which there are no overlapping intervals. Here X be any real number. Examples: Input: arr[] = {[1, 3], [2, 4], [4, 5], [5, 6]} Output: YES Explanation: We can add X = 1000 in [Tex]1^{st} [/Tex]and [Tex]3^{rd} [/Tex]intervals
9 min read
Generate two BSTs from the given array such that maximum height among them is minimum
Given an array of n integers where n is greater than 1, the task is to make two Binary Search Tree from the given array (in any order) such that the maximum height among the two trees is minimum possible and print the maximum height.Examples: Input: arr[] = {1, 2, 3, 4, 6} Output: 1 Input: arr[] = { 74, 25, 23, 1, 65, 2, 8, 99 } Output: 2 Approach:
4 min read
Find set of size K such that any value of the set is co-prime with any Array element
Given a set S of having numbers 1, 2, 3, . . ., N, and an integer K, the task is to form a set A by taking K values from S such that any pair formed by taking one value from S and another from A, is always coprime. (Two numbers are coprime if their GCD is 1). Note: If multiple solutions exist, print any of them, and if no such set exists, print -1.
10 min read
Find least non-overlapping number from a given set of intervals
Given an array interval of pairs of integers representing the starting and ending points of the interval of size N. The task is to find the smallest non-negative integer which is a non-overlapping number from the given set of intervals. Input constraints: [Tex]1 ≤ N ≤ 10^{5}0 ≤ interval[i] ≤ 10^{9} [/Tex] Examples: Input: interval = {{0, 4}, {6, 8}
15+ min read
Find a pair of overlapping intervals from a given Set
Given a 2D array arr[][] with each row of the form {l, r}, the task is to find a pair (i, j) such that the ith interval lies within the jth interval. If multiple solutions exist, then print anyone of them. Otherwise, print -1. Examples: Input: N = 5, arr[][] = { { 1, 5 }, { 2, 10 }, { 3, 10}, {2, 2}, {2, 15}}Output: 3 0Explanation: [2, 2] lies insi
11 min read
Minimize Cash Flow among a given set of friends who have borrowed money from each other
Given a number of friends who have to give or take some amount of money from one another. Design an algorithm by which the total cash flow among all the friends is minimized.  Example:  Following diagram shows input debts to be settled.  Above debts can be settled in following optimized way   The idea is to use Greedy algorithm where at every step,
15+ min read
Find the string among given strings represented using given encryption pattern
Given an array of strings arr[] of size N and an encrypted string str, the task is to find the correct string from the given array of strings whose encryption will give str where str is encrypted using the following rules: The starting characters form an integer representing the number of uppercase symbols In the decrypted string.The next 3 charact
8 min read
String matching with * (that matches with any) in any of the two strings
You are given two strings A and B. Strings also contains special character * . you can replace * with any alphabetic character. Finally, you have to tell whether it is possible to make both string same or not. Examples: Input : A = "gee*sforgeeks" B = "geeksforgeeks"Output :YesInput :A = "abs*" B = "abds"Output :NoExplanation: How we can solve abov
10 min read
Make the intervals non-overlapping by assigning them to two different processors
Given a list of intervals interval[] where each interval contains two integers L and R, the task is to assign intervals to two different processors such that there are no overlapping intervals for each processor. To assign the interval[i] to the first processor, print "F" and to assign it to the second processor, print "S".Note: If there is no poss
8 min read
Check if any permutation of N equals any power of K
Given a positive integer N and K where [Tex]2 \leq N \leq 10^{18} [/Tex] and [Tex]2 \leq K \leq N [/Tex] . The task is to check whether any permutation of digits of N equals any power of K. If possible return "True" otherwise return "False".Examples: Input: N = 96889010407, K = 7 Output: True Explanation: 96889010407 = 713 Input : N = 123456789, K
6 min read
Check whether the cost of going from any node to any other node via all possible paths is same
Given adjacency list representation of a directed graph, the task is to check whether the cost of going from any vertex to any other vertex via all possible paths is equal or not. If there is a cost c for going from vertex A to vertex B, then the cost to travel from vertex B to vertex A will be -c. Examples: Input: arr[][] = {{0, 2, 0, 1}, {-2, 0,
9 min read
Check if any permutation of a number without any leading zeros is a power of 2 or not
Given an integer N, the task is to check if any permutation of N without any leading zeros is a power of 2. If any such permutation of the given number exists, then print that permutation. Otherwise, print No. Examples: Input: N = 46Output: 64Explanation:The permutation of 46 which is perfect power of 2 is 64( = 26) Input: N = 75Output: NoExplanati
9 min read
Check if any K ranges overlap at any point
Given N ranges [L, R] and an integer K, the task is to check if there are any K ranges that overlap at any point. Examples: Input: ranges[][] = {{1, 3}, {2, 4}, {3, 4}, {7, 10}}, K = 3 Output: Yes 3 is a common point among the ranges {1, 3}, {2, 4} and {3, 4}. Input: ranges[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}, K = 2 Output: No Recommended: Pleas
13 min read
Find the larger exponential among two exponentials
Given four integers A, B, C and D. The task is to find which is greater AB or CD. Examples: Input: A = 2, B = 5, C = 4, D = 2 Output: 2^5 25 = 32 42 = 16 Input: A = 8, B = 29, C = 60, D = 59 Output: 60^59 Naive approach: Calculate the values of AB and CD then compare them. This approach will fail when the values are greater say 562145321457. Effici
4 min read
Repeated subtraction among two numbers
Given a pair of positive numbers x and y. We repeatedly subtract the smaller of the two integers from greater one until one of the integers becomes 0. The task is to count number of steps to before we stop (one of the numbers become 0). Examples : Input : x = 5, y = 13 Output : 6 Explanation : There are total 6 steps before we reach 0: (5,13) --
6 min read
Check if there is any common character in two given strings
Given two strings. The task is to check that is there any common character in between two strings. Examples: Input: s1 = "geeksforgeeks", s2 = "geeks" Output: Yes Input: s1 = "geeks", s2 = "for" Output: No Approach: Traverse the 1st string and map the characters of the string with its frequency, in this map characters act as a key and the frequency
8 min read
Minimum Set size for covering intervals
Given an array arr[] consisting of N ranges of the form [L, R], the task is to determine the size of the smallest set that contains at least 2 integers within each interval. Examples: Input: arr[] = { {1, 3}, {2, 5}, {1, 4} }Output: 2Explanation: Interval [1, 3] contains the numbers 1, 2, 3.Interval [2, 5] contains the numbers 2, 3, 4, 5.Interval [
7 min read
Find index of closest non-overlapping interval to right of each of given N intervals
Given an array arr[] of N intervals, the task is to calculate the index of the closest interval to the right of each of the given N intervals that do not overlap with the current interval. Examples: Input: arr[] = {{3, 4}, {2, 3}, {1, 2}}Output: -1 0 1Explanation: For the interval arr[0], there exists no interval to the right of it. For interval ar
7 min read
Count the number of intervals in which a given value lies
Given a 2D-array of [Tex]N [/Tex]integer intervals [Tex][L, R] [/Tex]and a value [Tex]V [/Tex]. For every interval [li, ri], the task is to check if V lies in between li and ri, both inclusive. The task is to print the count of intervals that satisfies this. Note: 1&lt;=li&lt;= riExamples: Input: arr[][] = {{1, 10}, {5, 10}, {15, 25}, {7, 12}, {20,
13 min read
Count points covered by given intervals
Consider an infinite x-y plane. Infinite people walk on the plane in an upward or +ve Y direction. At each integer point on the x-axis, only one person walks. Suppose, several barriers exist parallel to the x-axis. Barriers are provided as three triplets X1 - the x-point at which the barrier startsX2 - the x-point at which the barrier ends.Y - the
7 min read
Number of ways to distribute N Paper Set among M students
Given N students and a total of M sets of question paper where M ? N. All the M sets are different and every sets is available in sufficient quantity. All the students are sitting in a single row. The task is to find the number of ways to distribute the question paper so that if any M consecutive students are selected then each student has a unique
4 min read
Find maximum among x^(y^2) or y^(x^2) where x and y are given
Given X and Y whose values are greater than 2, the task is to find out which is maximum among [Tex]x^{y^{2}}[/Tex] and [Tex]y^{x^{2}}[/Tex] Consider that either x is greater than y or y is greater than x. So, print 1 if [Tex]x^{y^{2}}[/Tex] is greater or 2 if [Tex]y^{x^{2}}[/Tex]is greater. Examples: Input: X = 4, Y = 9 Output: 1 Input: X = 4, Y =
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg