Group points by distance threshold
NuroSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to efficiently group spatial points based on proximity using graph traversal or clustering techniques while managing computational complexity.
Problem Statement
You are given a list of 2D points points represented as [x, y] coordinates and a positive float threshold. Two points belong to the same group if the Euclidean distance between them is less than or equal to threshold. If point A is connected to point B, and point B is connected to point C, then A, B, and C all belong to the same group (transitive property).
Write a function group_points(points, threshold) that returns a list of lists, where each inner list contains the indices of the points that form a distinct group.
Function Signature
def group_points(points: List[List[float]], threshold: float) -> List[List[int]]:
Constraints
1 <= len(points) <= 1000-10^4 <= x, y <= 10^40 <= threshold <= 10^4
Examples
Example 1:
Input: points = [[0,0], [1,0], [5,5], [6,5]], threshold = 1.5
Output: [[0, 1], [2, 3]]
Explanation: [0,0] and [1,0] have distance 1.0 (<= 1.5). [5,5] and [6,5] have distance 1.0 (<= 1.5). No other pairs meet the criteria.
Example 2:
Input: points = [[0,0], [1,1], [2,2]], threshold = 1.5
Output: [[0, 1, 2]]
Explanation: Distance between [0,0] and [1,1] is ~1.41. Distance between [1,1] and [2,2] is ~1.41. Since both are <= 1.5, they form a single group.
Edge Cases
- A point with no neighbors should be in its own group.
threshold = 0(only identical points are grouped).
Hints
Hint 1
Consider this as a graph problem where points are nodes and an edge exists between two nodes if their distance is within the threshold.
Hint 2
You can use a Disjoint Set Union (DSU) data structure or perform a Breadth-First Search (BFS)/Depth-First Search (DFS) on the constructed adjacency list.
Hint 3
For the naive approach, calculate the distance between all pairs of points; what is the time complexity of this approach, and can you optimize it if the number of points were significantly larger?
Follow-up questions
- How would you optimize this solution if the number of points increased to 1,000,000?
- What changes would be required if the threshold was not a constant, but instead specific to each point?
- How would you handle the data if the points were stored in a streaming format rather than a static list?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.