Closest Pair of Points using Sweep Line Algorithm
Last Updated :
23 Jul, 2025
Given an array of N points in the plane, the task is to find a pair of points with the smallest distance between them, where the distance between two points (x1, y1) and (x2, y2) can be calculated as [(x1 - x2) ^ 2] + [(y1 - y2) ^ 2].
Examples:
Input: P[] = { {1, 2}, {2, 3}, {3, 4}, {5, 6}, {2, 1} }
Output: The smallest distance is 2.
Explanation: Distance between points as:
P[0] and P[1] = 2, P[0] and P[2] = 8, P[0] and P[3] = 32, P[0] and P[4] = 2
P[1] and P[2] = 2, P[1] and P[3] = 18, P[1] and P[4] = 4
P[2] and P[3] = 8, P[2] and P[4] = 10
P[3] and P[4] = 34
Minimum distance among them all is 2.
Input: P[] = { {0, 0}, {2, 1}, {1, 1} }
Output: The smallest distance is 1.
Approach: To solve the problem follow the below idea:
The idea is to use Sweep Line Algorithm to find the smallest distance between a pair of points. We can sort the points on the basis of their x-coordinates and start iterating over all the points in increasing order of their x-coordinates.
Suppose we are at the Kth point so all the points to the left of Kth point will be already processed. Let the minimum distance between 2 points found so far be D. So, to process the Kth point, we will consider only those points whose distance from Kth point < D. Maintain a set to store the previously processed points whose x-coordinates are less than D distance from Kth point. All the points in the set are ordered by their y-coordinates. In the below image, the light-green shaded region represents all the points which are available in the set.
Now to search for the points in the set which are less than D distance away from point K, we will consider only those points whose y-coordinates are less than D distance from Kth point (points having their y-coordinates in range (YK - D, YK + D)). This can be performed in O(logN) time using Binary Search on set. Iterate over all those points and if distance is less than D, then update the minimum distance. In the above image, the dark-green region represents all the points in the set whose y-coordinates are less than D distance from Kth point. The efficiency of the algorithm is based on the fact that this region will contain O(1) points on an average.
After iterating over all the points, return the smallest distance found between any 2 points.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// To find the closest pair of points
long long
closestPair(vector<pair<long long, long long> > coordinates,
int n)
{
// Sort points according to x-coordinates
sort(coordinates.begin(), coordinates.end());
// Set to store already processed points whose distance
// from the current points is less than the smaller
// distance so far
set<pair<long long, long long> > s;
long long squaredDistance = LLONG_MAX;
long long j = 0;
for (long long i = 0; i < n; ++i) {
// Find the value of D
long long D = ceil(sqrt(squaredDistance));
while (coordinates[i].first - coordinates[j].first >= D) {
s.erase({ coordinates[j].second, coordinates[j].first });
j += 1;
}
// Find the first point in the set whose y-coordinate is less than D distance from ith point
auto start
= s.lower_bound({ coordinates[i].second - D,
coordinates[i].first });
// Find the last point in the set whose y-coordinate is less than D distance from ith point
auto end
= s.upper_bound({ coordinates[i].second + D,
coordinates[i].first });
// Iterate over all such points and update the minimum distance
for (auto it = start; it != end; ++it) {
long long dx = coordinates[i].first - it->second;
long long dy = coordinates[i].second - it->first;
squaredDistance = min(squaredDistance, 1LL * dx * dx + 1LL * dy * dy);
}
// Insert the point as {y-coordinate, x-coordinate}
s.insert({ coordinates[i].second,
coordinates[i].first });
}
return squaredDistance;
}
// Driver code
int main()
{
// Points on a plane P[i] = {x, y}
vector<pair<long long, long long> > P = {
{ 1, 2 }, { 2, 3 }, { 3, 4 }, { 5, 6 }, { 2, 1 }
};
int n = P.size();
// Function call
cout << "The smallest distance is "
<< closestPair(P, n);
return 0;
}
Java
import java.util.*;
public class ClosestPair {
// To find the closest pair of points
public static long closestPair(List<long[]> coordinates, int n) {
// Sort points according to x-coordinates
Collections.sort(coordinates, Comparator.comparingLong(a -> a[0]));
// TreeSet to store already processed points whose distance
// from the current points is less than the smallest distance so far
TreeSet<long[]> set = new TreeSet<>(Comparator.comparingLong(a -> a[1]));
long squaredDistance = Long.MAX_VALUE;
int j = 0;
for (int i = 0; i < n; ++i) {
// Find the value of D
long D = (long) Math.ceil(Math.sqrt(squaredDistance));
while (coordinates.get(i)[0] - coordinates.get(j)[0] >= D) {
set.remove(new long[]{coordinates.get(j)[1], coordinates.get(j)[0]});
j += 1;
}
// Find the first point in the set whose y-coordinate is less than D distance from ith point
long[] lowerBound = new long[]{coordinates.get(i)[1] - D, Long.MIN_VALUE};
// Find the last point in the set whose y-coordinate is less than D distance from ith point
long[] upperBound = new long[]{coordinates.get(i)[1] + D, Long.MAX_VALUE};
// Iterate over all such points and update the minimum distance
for (long[] point : set.subSet(lowerBound, upperBound)) {
long dx = coordinates.get(i)[0] - point[1];
long dy = coordinates.get(i)[1] - point[0];
squaredDistance = Math.min(squaredDistance, dx * dx + dy * dy);
}
// Insert the point as {y-coordinate, x-coordinate}
set.add(new long[]{coordinates.get(i)[1], coordinates.get(i)[0]});
}
return squaredDistance;
}
public static void main(String[] args) {
// Points on a plane P[i] = {x, y}
List<long[]> P = new ArrayList<>();
P.add(new long[]{1, 2});
P.add(new long[]{2, 3});
P.add(new long[]{3, 4});
P.add(new long[]{5, 6});
P.add(new long[]{2, 1});
int n = P.size();
// Function call
System.out.println("The smallest distance is " + closestPair(P, n));
}
}
Python
import math
from sortedcontainers import SortedSet
# Point class for 2-D points
class Point:
def __init__(self, x, y) :
self.x = x
self.y = y
def closestPair(coordinates, n) :
# Sort points according to x-coordinates
coordinates.sort(key=lambda p: p.x)
# SortedSet to store already processed points whose distance
# from the current points is less than the smaller distance so far
s = SortedSet(key=lambda p: (p.y, p.x))
squaredDistance = 1e18
j = 0
for i in range(len(coordinates)):
# Find the value of D
D = math.ceil(math.sqrt(squaredDistance))
while j <= i and coordinates[i].x - coordinates[j].x >= D:
s.discard(Point(coordinates[j].x, coordinates[j].y))
j += 1
# Find the first point in the set whose y-coordinate is less than D distance from ith point
start = Point(coordinates[i].x, coordinates[i].y - D)
# Find the last point in the set whose y-coordinate is less than D distance from ith point
end = Point(coordinates[i].x, coordinates[i].y + D)
# Iterate over all such points and update the minimum distance
for it in s.irange(start, end):
dx = coordinates[i].x - it.x
dy = coordinates[i].y - it.y
squaredDistance = min(squaredDistance, dx * dx + dy * dy)
# Insert the point into the SortedSet
s.add(Point(coordinates[i].x, coordinates[i].y))
return squaredDistance
# Driver code
if __name__ == "__main__":
# Points on a plane P[i] = {x, y}
P = [
Point(1, 2),
Point(2, 3),
Point(3, 4),
Point(5, 6),
Point(2, 1)
]
n = 5
# Function call
print("The smallest distance is", closestPair(P, n))
JavaScript
// To find the closest pair of points
function closestPair(coordinates) {
// Sort points according to x-coordinates
coordinates.sort((a, b) => a[0] - b[0]);
// Array to store already processed points
let s = [];
let squaredDistance = Number.MAX_SAFE_INTEGER;
let j = 0;
for (let i = 0; i < coordinates.length; ++i) {
// Find the value of D
let D = Math.ceil(Math.sqrt(squaredDistance));
// Remove points from the set that are too far from the current point
while (coordinates[i][0] - coordinates[j][0] >= D) {
s.shift();
j += 1;
}
// Find points within the range [coordinates[i][1] - D, coordinates[i][1] + D]
let start = coordinates[i][1] - D;
let end = coordinates[i][1] + D;
// Iterate over all such points and update the minimum distance
for (let k = 0; k < s.length; ++k) {
let dx = coordinates[i][0] - s[k][1];
let dy = coordinates[i][1] - s[k][0];
squaredDistance = Math.min(squaredDistance, dx * dx + dy * dy);
}
// Insert the point into the set
s.push([coordinates[i][1], coordinates[i][0]]);
}
return squaredDistance;
}
// Driver code
function main() {
// Points on a plane P[i] = [x, y]
let P = [
[1, 2],
[2, 3],
[3, 4],
[5, 6],
[2, 1]
];
// Function call
console.log("The smallest distance is", closestPair(P));
}
// Call main function
main();
OutputThe smallest distance is 2
Time Complexity: O(N * logN), because we iterate over all the N points and logN for binary search to find the points whose Y coordinates are less than D distance away from the current point where D is the minimum distance between any two points covered so far.
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem