Line Sweep Technique Tutorials & Notes - Math - HackerEarth
Line Sweep Technique Tutorials & Notes - Math - HackerEarth
Signup and get free access to 100+ Tutorials and Practice Problems Start Now
2
LIVE EVENTS
All Tracks Math Geometry Line Sweep Technique
Math
Closest Pair
Problem: Find the closest pair of points in the given array of N distinct points
This problem can be solved by comparing all pairs of points , but then its complexity is O(N
2
)
So, we need a better algorithm for this . Here, we'll discuss it using line sweep technique.
For this problem, we can consider the points in the array as our events.
And in a set, we store the already visited points sorted by y coordinate.
So, rst we sort the points in x direction as we want our line to move towards right.
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 1/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
Now, suppose we have processed the points from 1 to N-1, and let h be the shortest distance we
have got so far. For Nth point, we want to nd points whose distance from Nth point is less than
or equal to h.
Now, we know we can only go till h distance from xN to nd such point, and in the y direction we
can go in h distance upwards and h distance downwards. So, all such points whose x coordinate
lie in [xN − h, xN ] and y coordinates lie in [yN − h, yN + h ] are what we are concerned with and
these form the active events of the set . All points in the set with x coordinates less than xN − h
are to be deleted . After this processing, we'll add the Nth point to the set.
One thing to note is that at any instance, the number of points which are active events is O(1)
(there can be atmost 5 points around a point which are active excluding the point itself).
Okay, that's a lot of theory, let's see this algo running
Initialize h as the distance between rst two points Update the value of h if present distance
between points is less than h
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 2/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
The red region in the image is the region containing points which are to be evaluated with the
current point.The points left to this region are removed from the set.
Following is the C++ code for above algorithm:
#define px second
#define py first
typedef pair<long long, long long> pairll;
pairll pnts [MAX];
int compare(pairll a, pairll b)
{
return a.px<b.px;
}
double closest_pair(pairll pnts[],int n)
{
sort(pnts,pnts+n,compare);
double best=INF;
set<pairll> box;
box.insert(pnts[0]);
int left = 0;
for (int i=1;i<n;++i)
{
while (left<i && pnts[i].px-pnts[left].px > best)
box.erase(pnts[left++]);
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 3/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
for(typeof(box.begin()) it=box.lower_bound(make_pair(pnts[i].py-
best, pnts[i].px-best));it!=box.end() && pnts[i].py+best>=it->py;it++)
best = min(best, sqrt(pow(pnts[i].py - it->py,
2.0)+pow(pnts[i].px - it->px, 2.0)));
box.insert(pnts[i]);
}
return best;
}
4. In the second for loop , we are iterating over all points whose x coordinates lie in [xN − h, xN ]
and y coordinates lie in [yN − h, yN + h ]. Finding the lower_bound takes O(logN ) and this loop
runs for atmost 5 times.
5. For each point, insert into the set. This step takes O(logN ) .
Union Of Rectangles:
Problem: Given a set of N axis aligned rectangles(edges of rectangles parallel to x axis or y axis),
nd the area of union of all of the rectangles. A rectangle is represented by two points , one
lower-left point and one upper-right point.
The events for this problem are the vertical edges.When we encounter a left edge, we do some
action and when we encounter a right edge, we do some other action.Left edge is represented by
lower-left point and right edge by upper-right point
We start our algorithm by sorting the events by x coordinates. When a lower left point of a
rectangle is hit (i.e., we encounter left edge of rectangle), we insert the rectangle into the set .
When we hit an upper right point of a rectangle (we encounter right edge of rectangle), we
remove the rectangle from the set. At any instance, the set contains only the rectangles which
intersect the sweep line (rectangles whose left edges are visited but right edges are not).
The area swept at any instance is = Δ y* Δ x where Δ y is the length of the sweep line which is
actually cut by the rectangle(s) (sum of the vertical lengths of the orange region, in the gure
below) and Δ x is the distance between two events of this sweep line.
But here we just know which are the rectangles intersecting the sweep line. So, here we have a
new problem: how to nd the length of the sweep line cut by the rectangles?
The solution to this problem is pretty the same we have been doing by now. We use the line
sweep technique to nd this but this time we apply it 90 degrees rotated, i.e., we sweep a
horizontal line from bottom to up . The events for this sweep line would be the horizontal edges
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 4/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
of the active rectangles(rectangles cut by vertical sweep line). When we encounter a bottom
horizontal edge of an active rectangle, we increment the counter (counter here maintains the
number of rectangles that overlap at current time) and we decrement it on top horizontal edge of
active rectangle. When the counter becomes zero from some non zero value, we have found cut
length of the vertical sweep line, so we add the area to our nal answer.
Let's see it running now:
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 5/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
The images above show how we're doing the horizontal sweep bottom up. Δ y is the sum of the
length of the two arrows shown in the last image. This we do, for all events of vertical sweep line.
This was our algorithm. So, let's come to implementation part. For every event of vertical sweep
line , we need to nd the length of the cut on the sweep line, that means we need to go for
horizontal sweep line. Here, we may use boolean array as our data structure because we would
have once sorted the rectangles in order of vertical edges(vertical sweep) and once in order of
horizontal edges(horizontal sweep), so we would have the sorting in both the directions.
Following is the C++ code for the algorithm:
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 6/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 7/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
else
//If it is a top edge
{
--cnt;
//the rectangle is no more overlapping, so remove it
if (cnt==0)
//Block ends
{
int delta_y =
(rects[events_h[j].ind][13].y-begin_y);//length of the vertical sweep line cut by
rectangles
area+=delta_x * delta_y;
}
}
}
in_set[c.ind] = (c.type==0);//If it is a left edge, the
rectangle is in the active set else not
}
return area;
}
By now, you would have understood somewhat how to use this technique, right?
Let's jump to one more problem that can be solved using this technique.
Convex Hull
Let S be a set of points. Then, convex hull is the smallest convex polygon which covers all the
points of S.
There exists an e cient algorithm for convex hull (Graham Scan) but here we discuss the same
idea except for we sort on the basis of x coordinates instead of angle.
The pseudo code for the algorithm is:
for i = 1, 2, ..., n:
while L contains at least two points and the sequence of last two points
of L and the point P[i] does not make a counter-clockwise turn:
remove the last point from L
append P[i] to L
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 8/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
while U contains at least two points and the sequence of last two points
of U and the point P[i] does not make a counter-clockwise turn:
remove the last point from U
append P[i] to U
Remove the last point of each list (it's the same as the first point of the
other list).
Concatenate L and U to obtain the convex hull of P.
Points in the result will be listed in counter-clockwise order.
struct Point {
double x, y;
};
bool compare(Point a,Point b)
{
return a.x<b.x || (a.x==b.x && a.y<b.y);
}
//Returns positive value if B lies to the left of OA, negative if B lies to the
right of OA, 0 if collinear
double cross(const Point &O, const Point &A, const Point &B)
{
return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
}
//Returns a list of points on the convex hull
vector<Point> convex_hull(vector<Point> P)
{
int n = P.size(), k = 0;
vector<Point> H(2*n);
sort(P.begin(), P.end(),compare);
// Build lower hull
for (int i = 0; i < n; ++i) {
while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 9/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
That was our convex hull using Andrew's algorithm, here we sorted using x coordinates for
sweeping our line rightwards. This was using our line sweep technique.
Complexity of this algorithm is O(N ∗ logN ) because of sorting. It may seem to be O(N
2
)
because of while loop inside but this loop runs for overall O(N ) as we are deleting points in this
loop and we have only N points , so it gives O(N ) .
Now you have got some taste of this technique, now try solving the attached problem. Do explore
this technique's application in some other problems.
Area of Rectangles
Given a set of N axis aligned rectangles, you need to nd the area of their union. Each rectangle
is represented by two points, one lower-left point and one upper-right point. The coordinates are
all integers.
Input:
First line consists of N denoting the number of rectangles.
Following N lines consist of x1,y1,x2,y2 each where (x1, y1) represents the lower-left point and
(x2, y2) represents the upper-right point of i th rectangle.
Output:
Print the area of the union of the rectangles.
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 10/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
Constraints:
4
1 ≤ N ≤ 10
1 ≤ x1 < x2 ≤ 10
5
<
5
1 ≤ y1 y2 ≤ 10
SAMPLE INPUT
3
2 1
4 2
2 3
4 5
1 4
3 6
SAMPLE OUTPUT
Enter your code or Upload your code as le. Save C (gcc 5.4.0)
1 /*
2 // Sample code to perform I/O:
3
4 scanf("%s", name); // Reading input from STDIN
5 printf("Hi, %s.\n", name); // Writing output to STDOUT
6
7 // Warning: Printing unwanted or ill-formatted data to output will cause the t
8 */
9
10 // Write your code here
11
1:1
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 11/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
Need Help ?
In case you feel you are stuck with the problem, you can view our editorial.
Remember this is just to help you out, in order to learn you should try your best.
VIEW EDITORIAL
Login/Signup to Comment
In closest pair of points problem, it is written, "the number of points which are active events is O(1)
(there can be atmost 5 points around a point which are active excluding the point itself)." How do
you conclude this ? what are those ve point ? I am not getting it . Plz help.
1 vote Reply Message Permalink
http://www.cs.mcgill.ca/~cs251/ClosestPair/proofbox.html
3 votes Reply Message Permalink
Press Careers
Reach Us
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 12/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 13/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 14/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 15/16
1/2/2018 Line Sweep Technique Tutorials & Notes | Math | HackerEarth
https://www.hackerearth.com/practice/math/geometry/line-sweep-technique/tutorial/ 16/16