Spaced Points Stream: Cancel a Nearby Point or Insert
Data Structure DesignAuto-graded · 19 test casesLast updated
Maintain a dynamic ordered set of numbers and, per arrival, find the smallest stored value in a closed window around it, deleting it or inserting the newcomer.
Spaced Points Stream
A set of real numbers on a number line starts out empty. Numbers arrive one at a time, and each arrival either cancels a number already in the set or is stored itself.
You are given a distance threshold d, a list of operation names operations, and a parallel list arguments. Entry arguments[i] is a list holding the arguments of operations[i].
Every operation name is "process", and its argument list holds a single number p. Handle process(p) as follows:
- Look at the stored numbers
qthat lie in the closed windowp - d <= q <= p + d. Compute both bounds as ordinary floating-point values, and use inclusive comparisons. - If at least one stored number is in the window, remove the smallest such number from the set, do not store
p, and recordFalse. - Otherwise, store
pand recordTrue.
Return the list of recorded booleans, one per operation, in order.
If an operation name is anything other than "process", raise a ValueError.
Clarifications
- Equal values are at distance 0, so for
d >= 0a value equal to a stored one cancels it. - If
dis negative, the window is empty, so every call stores its point and returnsTrue. Duplicate values can then be stored, and each stored copy counts separately. - When several stored numbers fall in the window, always remove the smallest one. This fixed rule makes the output unique.
Constraints
- Up to 10^5 operations.
len(operations) == len(arguments), and each argument list has exactly one number.- Points and
dare floating-point numbers (integers may appear as well). - Each operation should run in better than O(N) time, so a full scan of the stored points per call is too slow. Target O(log N) per operation.
Examples
Example 1
Input: track_spaced_points(2, ['process', 'process', 'process', 'process'], [[5], [6], [10], [12]])
Output: [True, False, True, False]
Example 2
Input: track_spaced_points(2, ['process', 'process', 'process', 'process', 'process'], [[5], [6], [10], [12], [11]])
Output: [True, False, True, False, True]
Example 3
Input: track_spaced_points(0, ['process', 'process', 'process', 'process'], [[3.5], [3.5], [3.5], [4]])
Output: [True, False, True, True]
Hints
Hint 1
Every stored number that could cancel the new point lies in the closed window [p - d, p + d]. You do not need to list them all, only the smallest one.
Hint 2
Find the smallest stored value that is >= p - d (a lower bound). If it exists and is <= p + d, it is the smallest value in the window. Otherwise the window is empty.
Hint 3
You need an ordered set with insert, delete, and lower-bound all in O(log n). A plain sorted list with insertion is O(n) per update, so use a balanced BST such as an AVL tree, or a sorted-container library if allowed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep the stored numbers in an ordered structure that supports insert, delete, and "smallest key >= x" (lower bound), each in O(log n).
For an arriving point p, every stored number that could cancel it lies in [p - d, p + d]. Only the smallest number in that window matters, and one lower-bound query finds it:
- Let
cbe the smallest stored value that is>= p - d. - If
cexists andc <= p + d, thencis the smallest value in the window. Delete it and outputFalse. - Otherwise the window is empty. Insert
pand outputTrue.
Why it is correct
- Completeness. If some stored
qlies in the window, thenq >= p - d, so the lower bound exists and is<= q <= p + d. The check therefore succeeds whenever the window is non-empty. - Soundness. If the check succeeds, then
p - d <= c <= p + d, socreally is in the window. - Tie-break.
cis the smallest stored value at or abovep - d, so it is the minimum of the window, which is exactly the required choice.
For d >= 0, a point is stored only when nothing lies within d of it, so stored points are always more than d apart. For negative d, the window is empty every time, so duplicates can pile up. Each tree node therefore keeps a multiplicity counter, and deleting one copy just decrements it.
Data structure
Python has no built-in balanced BST, and bisect.insort on a list costs O(n) per update. The reference uses a small AVL tree with insert, delete, and lower_bound. In the two-child delete case, the successor's key and count are copied into the node and the successor's count is set to 1, so the recursive delete removes the successor node fully.
Complexity
- Time: O(log n) per operation, so O(m log m) for m operations.
- Space: O(n) for the stored points, with recursion depth O(log n).
Reference solution
from typing import List
def track_spaced_points(d: float, operations: List[str], arguments: List[List[float]]) -> List[bool]:
class Node:
__slots__ = ("key", "count", "left", "right", "height")
def __init__(self, key):
self.key = key
self.count = 1
self.left = None
self.right = None
self.height = 1
def height(node):
return node.height if node else 0
def update(node):
node.height = 1 + max(height(node.left), height(node.right))
return node
def rotate_right(node):
child = node.left
node.left = child.right
child.right = node
update(node)
return update(child)
def rotate_left(node):
child = node.right
node.right = child.left
child.left = node
update(node)
return update(child)
def balance(node):
if not node:
return None
update(node)
factor = height(node.left) - height(node.right)
if factor > 1:
if height(node.left.left) < height(node.left.right):
node.left = rotate_left(node.left)
return rotate_right(node)
if factor < -1:
if height(node.right.right) < height(node.right.left):
node.right = rotate_right(node.right)
return rotate_left(node)
return node
def insert(node, key):
if not node:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
else:
node.count += 1
return node
return balance(node)
def minimum(node):
while node.left:
node = node.left
return node
def delete(node, key):
if key < node.key:
node.left = delete(node.left, key)
elif key > node.key:
node.right = delete(node.right, key)
elif node.count > 1:
node.count -= 1
return node
elif not node.left:
return node.right
elif not node.right:
return node.left
else:
successor = minimum(node.right)
node.key = successor.key
node.count = successor.count
successor.count = 1
node.right = delete(node.right, successor.key)
return balance(node)
def lower_bound(node, value):
result = None
while node:
if node.key >= value:
result = node
node = node.left
else:
node = node.right
return result
root = None
out = []
for operation, args in zip(operations, arguments):
if operation != "process":
raise ValueError("unsupported operation")
point = args[0]
candidate = lower_bound(root, point - d)
if candidate is not None and candidate.key <= point + d:
root = delete(root, candidate.key)
out.append(False)
else:
root = insert(root, point)
out.append(True)
return out