Streaming Points: Remove Any Pair Within a Distance
GoogleSoftware Engineer · OnsiteLast updated
This problem tests the ability to maintain and query a dynamic sorted collection of points to perform efficient proximity-based removals.
Problem Statement
You are building a system that processes a stream of 1D points on a number line. You need to implement a class PointProcessor that supports two operations: adding a new point and removing a point. When a new point is added, if there is an existing point P in the system such that the distance |new_point - P| <= D (where D is a predefined threshold), you must remove P from the system instead of adding the new point. If multiple such points exist, you can remove any one of them. If no such point exists, add the new point to the system.
Interface
class PointProcessor:
def __init__(self, d: float):
"""Initializes the processor with distance threshold d."""
self.d = d
def process(self, point: float) -> bool:
"""
If a point exists in the system within distance d,
remove it and return False. Otherwise, add the point
and return True.
"""
Examples
Example 1:
D = 2.0process(5.0)-> returnsTrue(System:{5.0})process(6.0)-> returnsFalse(Distance|6.0 - 5.0| = 1.0True(System:{10.0}`)process(12.0)->True(System:{10.0, 12.0})process(11.0)->False(Distance to 10.0 is 1.0, remove 10.0, System:{12.0})
Constraints
- Number of operations: up to 10^5.
- Points are floating-point numbers.
- Time complexity should be better than O(N) per operation.
Edge Cases
- Points with the exact same value.
- Multiple points within range D (the problem allows removing any valid candidate).
Hints
Hint 1
Consider using a data structure that keeps elements in sorted order to perform efficient range queries.
Hint 2
In languages like C++ or Java, `std::set` or `TreeSet` provide methods to find the ceiling or floor of a value in O(log N) time.
Hint 3
Check both the closest point greater than or equal to the new point and the closest point smaller than or equal to the new point.
Follow-up questions
- How would your approach change if you were required to remove the point with the smallest distance instead of 'any' valid point?
- What are the implications of using floating-point numbers versus integers for these distance comparisons?
- How would you adapt this logic if the points were 2D coordinates and the distance was Euclidean?
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.