Open In App

Count points covered by given intervals

Last Updated : 09 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 starts
  • X2 – the x-point at which the barrier ends.
  • Y – the point on the Y axis where the barrier lies.

Calculate how many people will get stuck at any point due to the barriers. The use of extra space to keep track of different points on x-axis is not allowed. Examples:

Input : barriers[] = {{3 6 2}, {-7 4 3}
Output : 14
The barrier from 3 to 6 blocks 3, 4, 5, 6, 
so 4 persons blocked till now.
The barrier from -7 to 4 blocks -7,-6,-5,-4,-
3, -2, -1, 0, 1, 2, 3, 4. But, 3 and 4 have 
already been blocked.
So, total persons blocked is 14.

Asked in: Microsoft IDC Internship. 

A simple approach is to use a very long array initialized to zero. Then we can mark those values by 1 which are in the barrier by looping through each barrier. This would solve the case of overlapping of barriers. But we cannot use another array as mentioned before. Thus, we use sorting and simple math. Following are the steps: 1. Sort all barriers by x1 (Starting point) 2. After sorting, 3 cases arrive: ……I. The next barrier does not overlap with the previous. In this case, we simply add count of points covered by current barrier. ……II. The next barrier partly overlaps the previous one. In this point we add non-overlapping points covered by current barrier. ……III. The next barrier completely overlaps the previous barrier. In this case, we simply ignore current barrier. Below is the implementation of above approach. 

CPP




// CPP program to find number of people
// that are stopped by barriers
#include <bits/stdc++.h>
using namespace std;
 
struct Barrier
{
    int x1, x2, y;
};
 
// Compares two Barriers according to x1
bool compareBarrier(Barrier b1, Barrier b2)
{
    return (b1.x1 < b2.x1);
}
 
// Returns number of people blocked by
// array of barriers arr[0..n-1]
int countStopped(Barrier arr[], int n)
{
    // Sort barriers according to x1.
    sort(arr, arr+n, compareBarrier);
 
    // End point of previous barrier
    // Initializing with some value
    // smaller than lowest x1.
    int prev_end = arr[0].x1 - 1;
 
    // Traverse through all bariers
    int count = 0;
    for (int i=0; i<n; i++)
    {
        // If current barrier doesn't overlap
        // with previous
        if (prev_end < arr[i].x1)
        {
            count += (arr[i].x2 - arr[i].x1 + 1);
            prev_end = arr[i].x2;
        }
 
        // If current barrier overlaps and
        // blocks some more people
        else if (prev_end < arr[i].x2)
        {
            count += (arr[i].x2 - prev_end);
            prev_end = arr[i].x2;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    Barrier arr[] = {{3, 6, 2}, {-7, 4, 3}};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << countStopped(arr, n);
    return 0;
}


Java




import java.io.*;
import java.util.*;
 
class Barrier {
    int x1, x2, y;
 
    Barrier(int x1, int x2, int y) {
        this.x1 = x1;
        this.x2 = x2;
        this.y = y;
    }
}
 
class GFG {
    // Compares two Barriers according to x1
    static boolean compareBarrier(Barrier b1, Barrier b2) {
        return (b1.x1 < b2.x1);
    }
 
    // Returns number of people blocked by
    // array of barriers arr[0..n-1]
    static int countStopped(Barrier[] arr, int n) {
        // Sort barriers according to x1.
        Arrays.sort(arr, new Comparator<Barrier>() {
            @Override
            public int compare(Barrier b1, Barrier b2) {
                return Integer.compare(b1.x1, b2.x1);
            }
        });
 
        // End point of previous barrier
        // Initializing with some value
        // smaller than lowest x1.
        int prev_end = arr[0].x1 - 1;
 
        // Traverse through all barriers
        int count = 0;
        for (int i = 0; i < n; i++) {
            // If current barrier doesn't overlap
            // with previous
            if (prev_end < arr[i].x1) {
                count += (arr[i].x2 - arr[i].x1 + 1);
                prev_end = arr[i].x2;
            }
 
            // If current barrier overlaps and
            // blocks some more people
            else if (prev_end < arr[i].x2) {
                count += (arr[i].x2 - prev_end);
                prev_end = arr[i].x2;
            }
        }
 
        return count;
    }
 
    // Driver code
    public static void main(String[] args) {
        Barrier[] arr = {new Barrier(3, 6, 2), new Barrier(-7, 4, 3)};
        int n = arr.length;
        System.out.println(countStopped(arr, n));
    }
}


Python3




from typing import List
 
class Barrier:
    def __init__(self, x1: int, x2: int, y: int):
        self.x1 = x1
        self.x2 = x2
        self.y = y
 
# Compares two Barriers according to x1
def compareBarrier(b1: Barrier, b2: Barrier) -> bool:
    return b1.x1 < b2.x1
 
# Returns number of people blocked by array of barriers arr[0..n-1]
def countStopped(arr: List[Barrier], n: int) -> int:
    # Sort barriers according to x1.
    arr.sort(key=lambda x: x.x1)
 
    # End point of previous barrier
    # Initializing with some value
    # smaller than lowest x1.
    prev_end = arr[0].x1 - 1
 
    # Traverse through all barriers
    count = 0
    for i in range(n):
        # If current barrier doesn't overlap with previous
        if prev_end < arr[i].x1:
            count += (arr[i].x2 - arr[i].x1 + 1)
            prev_end = arr[i].x2
 
        # If current barrier overlaps and blocks some more people
        elif prev_end < arr[i].x2:
            count += (arr[i].x2 - prev_end)
            prev_end = arr[i].x2
 
    return count
 
# Driver code
if __name__ == '__main__':
    arr = [Barrier(3, 6, 2), Barrier(-7, 4, 3)]
    n = len(arr)
    print(countStopped(arr, n))


C#




// C# program  for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
 
class Barrier
{
    public int x1, x2, y;
 
    public Barrier(int x1, int x2, int y)
    {
        this.x1 = x1;
        this.x2 = x2;
        this.y = y;
    }
}
 
class GFG
{
    // Compares two Barriers according to x1
    static bool CompareBarrier(Barrier b1, Barrier b2)
    {
        return (b1.x1 < b2.x1);
    }
 
    // Returns number of people blocked by
    // array of barriers arr[0..n-1]
    static int CountStopped(Barrier[] arr, int n)
    {
        // Sort barriers according to x1.
        Array.Sort(arr, (b1, b2) => b1.x1.CompareTo(b2.x1));
 
        // End point of previous barrier
        // Initializing with some value
        // smaller than lowest x1.
        int prev_end = arr[0].x1 - 1;
 
        // Traverse through all barriers
        int count = 0;
        for (int i = 0; i < n; i++)
        {
            // If current barrier doesn't overlap
            // with previous
            if (prev_end < arr[i].x1)
            {
                count += (arr[i].x2 - arr[i].x1 + 1);
                prev_end = arr[i].x2;
            }
 
            // If current barrier overlaps and
            // blocks some more people
            else if (prev_end < arr[i].x2)
            {
                count += (arr[i].x2 - prev_end);
                prev_end = arr[i].x2;
            }
        }
 
        return count;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        Barrier[] arr = {new Barrier(3, 6, 2), new Barrier(-7, 4, 3)};
        int n = arr.Length;
        Console.WriteLine(CountStopped(arr, n));
    }
}
 
// This code is contributed by princekumaras


Javascript




// JS equivalent of the above code
class Barrier {
    constructor(x1, x2, y) {
        this.x1 = x1;
        this.x2 = x2;
        this.y = y;
    }
}
 
// Compares two Barriers according to x1
function compareBarrier(b1, b2) {
    return b1.x1 < b2.x1;
}
 
// Returns number of people blocked by array of barriers arr[0..n-1]
function countStopped(arr, n) {
    // Sort barriers according to x1.
    arr.sort((x1, x2) => x1.x1 - x2.x1);
     
    // End point of previous barrier
    // Initializing with some value
    // smaller than lowest x1.
    let prev_end = arr[0].x1 - 1;
 
    // Traverse through all barriers
    let count = 0;
    for (let i = 0; i < n; i++) {
        // If current barrier doesn't overlap with previous
        if (prev_end < arr[i].x1) {
            count += (arr[i].x2 - arr[i].x1 + 1);
            prev_end = arr[i].x2;
 
        // If current barrier overlaps and blocks some more people
        } else if (prev_end < arr[i].x2) {
            count += (arr[i].x2 - prev_end);
            prev_end = arr[i].x2;
        }
    }
 
    return count;
}
 
// Driver code
let arr = [new Barrier(3, 6, 2), new Barrier(-7, 4, 3)];
let n = arr.length;
console.log(countStopped(arr, n));


Output :

14

We can easily note that there is no importance of y in the question, so it may not be stored. Time Complexity : O(n Log n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads