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 :

seg

  • 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 :

seg2

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

Approach:

  • We can do this by using logic similar to prefix sum.
  • Let’s represent a segment with (l, r). Form a vector of pairs, for each segment push two pairs in vector with values (l, +1) ans (r + 1, -1).
  • Sort the points in ascending order, but we also need it’s position so mapped it with it’s position.
  • Sort the segment vector in descending order because we iterate on it from back.
  • Make a variable count of segments, which is initially zero.
  • Then, we will iterate on the point and pop the pair from the segment vector until it’s first value is less than equal to current point and add it’s second value to the count.
  • Finally, Store the values of count in an array to his respective position and print the array.

Below is the implementation of the above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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]<<" ";
     }
}
  
// Funtion 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;

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 = " ")
  
# Funtion 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

chevron_right


Output:

0 3 1

Time Complexity: O(s + p)

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : bgangwar59

Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.