×

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each other. This problem arises in a number of applications. In air traffic control, for example, you might want to keep an eye out for planes flying too close together, as this could indicate a collision.

The most basic brute force solution is to compute the distance between each pair and return the smallest value. We can calculate the shortest distance using the Divide and Conquer strategy in O(N log N) time. This post goes over an O(n x (Logn)2) method. We will discuss an O(N log N) approach in a separate post.

Here is a code with appropriate comments to help you guide through the entire code and approach.

The algorithm calculates the distance between the nearest pair of points among the n points given.

The strategy employed -> Divide and conquer

The points are sorted first based on Xco-ords and then separately based on Yco-ords.

And, using the divide and conquer method, the shortest distance is obtained recursively.

The closest points may be on opposite sides of the partition.

This case was handled by forming a strip of points whose Xco-ords distance from the mid-points. Xco-ords is less than closest pair dis. To reduce sorting time, points sorted by Yco-ords are used in this step.

The closest pair distance is found in the point strip.

(closest_in_strip)


min(closest_pair_dis, closest_in_strip) would be the final answer.


Time complexity: O(n * log n)
"""




def euclidean_distance_sqr(point1, point2):
    return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2




def column_based_sort(array, column=0):
    return sorted(array, key=lambda x: x[column])




def dis_between_closest_pair(points, points_counts, min_dis=float("inf")):
    for i in range(points_counts - 1):
        for j in range(i + 1, points_counts):
            current_dis = euclidean_distance_sqr(points[i], points[j])
            if current_dis < min_dis:
                min_dis = current_dis
    return min_dis




def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")):
    for i in range(min(6, points_counts - 1), points_counts):
        for j in range(max(0, i - 6), i):
            current_dis = euclidean_distance_sqr(points[i], points[j])
            if current_dis < min_dis:
                min_dis = current_dis
    return min_dis




def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts):
    # base case
    if points_counts <= 3:
        return dis_between_closest_pair(points_sorted_on_x, points_counts)


    # recursion
    mid = points_counts // 2
    closest_in_left = closest_pair_of_points_sqr(
        points_sorted_on_x, points_sorted_on_y[:mid], mid
    )
    closest_in_right = closest_pair_of_points_sqr(
        points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid
    )
    closest_pair_dis = min(closest_in_left, closest_in_right)
    cross_strip = []
    for point in points_sorted_on_x:
        if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis:
            cross_strip.append(point)


    closest_in_strip = dis_between_closest_in_strip(
        cross_strip, len(cross_strip), closest_pair_dis
    )
    return min(closest_pair_dis, closest_in_strip)




def closest_pair_of_points(points, points_counts):
    points_sorted_on_x = column_based_sort(points, column=0)
    points_sorted_on_y = column_based_sort(points, column=1)
    return (
        closest_pair_of_points_sqr(
            points_sorted_on_x, points_sorted_on_y, points_counts
        )
    ) ** 0.5




if __name__ == "__main__":
    points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
    print("Distance:", closest_pair_of_points(points, len(points)))

Time Complexity

Let T be the time complexity of the preceding algorithm (n). Assume we're using an O(N log N) sorting algorithm. The preceding algorithm divides all points into two sets and calls for two sets recursively. It finds the strip in O(n) time after dividing, sorts the strip in O(N log N) time, and finally finds the closest points in the strip in O(n) time. As a result, T(n) can be written as follows.

  • T(n) = 2T(n/2) + O(n) + O(nLogn) + O(n)
  • T(n) = 2T(n/2) + O(nLogn)
  • T(n) = T(n x Logn x Logn)

Related Topics

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

Dynamic Typing in Python

Many key factors for developing a great programming language include how it manages its memory space. This memory space largely depends on empty memory boxes called variables that one creates...

3 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

Hog Descriptor Opencv Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Python Dictionary get() method

Python Dictionary get() method The dictionary.get() method returns the value of the item with the specified key. Syntax dictionary.get(keyname, value) Parameter keyname- This parameter represents the key to be searched in the dictionary. value- The parameter...

1 minute read.

How to build a Virtual Assistant Using Python

What is a virtual assistant? A virtual assistant is a new and very interesting concept in today’s world. When we hear the word “Virtual Assistant”, we can easily visualize “Jarvis or...

8 minutes read.

How to Download all Modules in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Python any() Function

Python any() Function The any() function in Python returns a boolean value ‘True’ if any element of the iterable is true or if the iterable is empty, else it returns False. Syntax any(iterable) Parameter Iterable: An iterable object (list, tuple, dictionary) Return This...

1 minute read.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

2 minutes read.