Open In App

Find number of segments covering each point in an given array

Given segments and some points, for each point find the number of segments covering that point.

A segment (l, r) covers a point x if and only if l < = x < = r.

Examples: 



Input: Segments = {{0, 3}, {1, 3}, {3, 8}}, 
Points = {-1, 3, 8}.
Output : {0, 3, 1}
Explanation :
 



 

  • No segments passing through point -1
  • All the segments passing through point 3
  • Segment 3rd passing through point 8

Input: Segments = {{1, 3}, {2, 4}, {5, 7}}, 
Points = {0, 2, 5}.
Output: {0, 2, 1}
Explanation :
 

 

  • No segments passing through point 0
  • 1st and 2nd segment passing through point 2
  • Segment 3rd passing through point 5

Approach:

Below is the implementation of the above approach. 




// C++ program to find the number of
// segments covering each points
#include<bits/stdc++.h>
using namespace std;
 
// Function to print an array
void PrintArray(int n,int arr[])
{
     for(int i = 0; i < n; i++)
     {
         cout<<arr[i]<<" ";
     }
}
 
// Function prints number of segments
// covering by each points
void NumberOfSegments(vector<pair<int,int> >segments,
                      vector<int>points, int s, int p)
{
   vector< pair<int, int> >pts, seg;
     
   // Pushing points and index in
   // vector as a pairs
   for(int i = 0; i < p; i++)
   {
      pts.push_back({points[i], i});;
   }
     
   for(int i = 0; i < s; i++)
   {
      // (l,+1)
      seg.push_back({segments[i].first, 1});
      // (r+1,-1)
      seg.push_back({segments[i].second+1, -1});
   }
     
   // Sort the vectors
   sort(seg.begin(), seg.end(),
        greater<pair<int,int>>());
   sort(pts.begin(),pts.end());
     
   int count = 0;
   int ans[p];
     
   for(int i = 0; i < p; i++)
   {
        int x = pts[i].first;
        
        while(!seg.empty() &&
              seg.back().first <= x)
        {
            count+= seg.back().second;
            seg.pop_back();
        }
        ans[pts[i].second] = count;
   }
     
   // Print the answer
   PrintArray(p, ans);
   
}
 
//Driver code
int main()
{
  // Initializing vector of pairs
  vector<pair<int,int>>seg;
     
  // Push segments
  seg.push_back({0, 3});
  seg.push_back({1, 3});
  seg.push_back({3, 8});
     
  // Given points
  vector<int>point{-1, 3, 7};
     
  int s = seg.size();
  int p = point.size();
     
  NumberOfSegments(seg, point, s, p);
     
  return 0;
}




// Java program to find the number of 
// segments covering each points
import java.util.*;
import java.lang.*;
 
class GFG{
  
// Function to print an array
static void PrintArray(int n,int arr[])
{
    for(int i = 0; i < n; i++)
    {
        System.out.print(arr[i] + " ");
    }
}
 
// Function prints number of segments
// covering by each points
static void NumberOfSegments(ArrayList<int[]> segments,
                         int[] points, int s, int p)
{
    ArrayList<int[]> pts = new ArrayList<>(),
                     seg = new ArrayList<>();
     
    // Pushing points and index in
    // vector as a pairs
    for(int i = 0; i < p; i++)
    {
        pts.add(new int[]{points[i], i});
    }
     
    for(int i = 0; i < s; i++)
    {
        // (l,+1)
        seg.add(new int[]{segments.get(i)[0], 1});
         
        // (r+1,-1)
        seg.add(new int[]{segments.get(i)[1] + 1, -1});
    }
     
    // Sort the vectors
    Collections.sort(seg, (a, b) -> b[0] - a[0]);
    Collections.sort(pts, (a, b) -> a[0] - b[0]);
     
    int count = 0;
    int[] ans = new int[p];
     
    for(int i = 0; i < p; i++)
    {
        int x = pts.get(i)[0];
         
        while (seg.size() != 0 &&
               seg.get(seg.size() - 1)[0] <= x)
        {
            count += seg.get(seg.size() - 1)[1];
            seg.remove(seg.size() - 1);
        }
        ans[pts.get(i)[1]] = count;
    }
     
    // Print the answer
    PrintArray(p, ans);
}
 
// Driver code
public static void main(String[] args)
{
     
    // Initializing vector of pairs
    ArrayList<int[]>seg = new ArrayList<>();
     
    // Push segments
    seg.add(new int[]{0, 3});
    seg.add(new int[]{1, 3});
    seg.add(new int[]{3, 8});
     
    // Given points
    int[] point = {-1, 3, 7};
     
    int s = seg.size();
    int p = point.length;
     
    NumberOfSegments(seg, point, s, p);
}
}
 
// This code is contributed by offbeat




# Python3 program to find the number
# of segments covering each point
 
# Function to print an array
def PrintArray(n, arr):
     
    for i in range(n):
        print(arr[i], end = " ")
 
# Function prints number of segments
# covering by each points
def NumberOfSegments(segments, points, s, p):
     
    pts = []
    seg = []
     
    # Pushing points and index in
    # vector as a pairs
    for i in range(p):
        pts.append([points[i], i])
 
    for i in range(s):
         
        # (l, +1)
        seg.append([segments[i][0], 1])
         
        # (r+1, -1)
        seg.append([segments[i][1] + 1, -1])
 
    # Sort the vectors
    seg.sort(reverse = True)
    pts.sort(reverse = False)
     
    count = 0
    ans = [0 for i in range(p)]
 
    for i in range(p):
        x = pts[i][0]
 
        while(len(seg) != 0 and
          seg[len(seg) - 1][0] <= x):
                   
            count += seg[len(seg) - 1][1]
            seg.remove(seg[len(seg) - 1])
             
        ans[pts[i][1]] = count
         
    # Print the answer
    PrintArray(p, ans)
 
# Driver code
if __name__ == '__main__':
     
    # Initializing vector of pairs
    seg = []
 
    # Push segments
    seg.append([ 0, 3 ])
    seg.append([ 1, 3 ])
    seg.append([ 3, 8 ])
         
    # Given points
    point = [ -1, 3, 7 ]
         
    s = len(seg)
    p = len(point)
         
    NumberOfSegments(seg, point, s, p)
 
# This code is contributed by Bhupendra_Singh




// C# program to find the number of
// segments covering each points
using System;
using System.Collections.Generic;
 
namespace ConsoleApp1
{
    class Program
    {
        // Function to print an array
        static void PrintArray(int[] arr)
        {
            foreach (int x in arr)
            {
                Console.Write(x + " ");
            }
        }
 
        // Function to find the number of segments covering each points
        static void NumberOfSegments(List<Tuple<int, int>> segments, int[] points)
        {
            List<Tuple<int, int>> pts = new List<Tuple<int, int>>();
            List<Tuple<int, int>> seg = new List<Tuple<int, int>>();
 
            // Pushing points and index in
            // list as a tuples
            for (int i = 0; i < points.Length; i++)
            {
                pts.Add(Tuple.Create(points[i], i));
            }
 
            for (int i = 0; i < segments.Count; i++)
            {
                // (l,+1)
                seg.Add(Tuple.Create(segments[i].Item1, 1));
                // (r+1,-1)
                seg.Add(Tuple.Create(segments[i].Item2 + 1, -1));
            }
 
            // Sort the lists
            seg.Sort((x, y) => y.Item1.CompareTo(x.Item1));
            pts.Sort();
 
            int count = 0;
            int[] ans = new int[points.Length];
 
            for (int i = 0; i < points.Length; i++)
            {
                int x = pts[i].Item1;
 
                while (seg.Count > 0 && seg[seg.Count - 1].Item1 <= x)
                {
                    count += seg[seg.Count - 1].Item2;
                    seg.RemoveAt(seg.Count - 1);
                }
 
                ans[pts[i].Item2] = count;
            }
 
            // Print the answer
            PrintArray(ans);
        }
 
        static void Main(string[] args)
        {
            // Initializing list of tuples
            List<Tuple<int, int>> seg = new List<Tuple<int, int>>();
 
            // Push segments
            seg.Add(Tuple.Create(0, 3));
            seg.Add(Tuple.Create(1, 3));
            seg.Add(Tuple.Create(3, 8));
 
            // Given points
            int[] point = { -1, 3, 7 };
 
            NumberOfSegments(seg, point);
 
            Console.ReadLine();
        }
    }
}




<script>
 
// JavaScript program to find the number of
// segments covering each points
 
// Function to print an array
function PrintArray(n,arr)
{
    for(let i = 0; i < n; i++)
    {
        document.write(arr[i]," ");
    }
}
 
// Function prints number of segments
// covering by each points
function NumberOfSegments(segments,points,s,p)
{
let pts = [];
let seg = [];
     
// Pushing points and index in
// vector as a pairs
for(let i = 0; i < p; i++)
{
    pts.push([points[i], i]);
}
     
for(let i = 0; i < s; i++)
{
    // (l,+1)
    seg.push([segments[i][0], 1]);
    // (r+1,-1)
    seg.push([segments[i][1]+1, -1]);
}
     
// Sort the vectors
 
seg.sort((a,b) => b[0]-a[0]);
pts.sort((a,b) => a[0]-b[0]);
     
let count = 0;
let ans = new Array(p);
     
for(let i = 0; i < p; i++)
{
        let x = pts[i][0];
         
        while(seg.length>0 && seg[seg.length-1][0] <= x)
        {
            count+= seg[seg.length-1][1];
            seg.pop();
        }
        ans[pts[i][1]] = count;
}
     
// Print the answer
PrintArray(p, ans);
 
}
 
// Driver code
 
// Initializing vector of pairs
let seg = [];
     
// Push segments
seg.push([0, 3]);
seg.push([1, 3]);
seg.push([3, 8]);
     
// Given points
let point = [-1, 3, 7];
     
let s = seg.length;
let p = point.length;
     
NumberOfSegments(seg, point, s, p);
 
// This code is contributed by shinjanpatra.
</script>

Output: 
0 3 1

 

Time Complexity: O(s*log(s) + p*log(p)), where s is the number of segments and p is the number of points.
Auxiliary Space: O(s + p).


Article Tags :