Validated Config-Driven LiDAR Scan Processor
Arrays & HashingAuto-graded · 14 test casesLast updated
Validate a declarative list of crop and rigid-transform steps up front, then apply them in order to a point list while tracking metadata, without mutating the inputs.
Validated Config-Driven LiDAR Scan Processor
A perception stack cleans up raw LiDAR scans with an ordered list of steps described as plain data. Implement a function that checks the whole description first, then runs it on a scan.
Input
points: a list of points. Each point is a list of numbers[x, y, z, ...]with at least three values. Values after the first three are extra channels (intensity, ring ID, and so on). All points must have the same length.metadata: a dictionary describing the scan. It may contain keys such as"frame_id"and"applied_transforms"(a list of earlier step records), plus any other keys.config: a list of step descriptions. Each one is a dictionary with exactly the keys"name"and"params".
Supported steps
CropBoundingBox, with params containing exactly min_bound and max_bound.
- Each bound is a list of exactly 3 finite numbers (not booleans).
- For every axis,
min_bound[i] <= max_bound[i]must hold (equality is allowed). - Keep a point only if
min_bound[i] <= point[i] <= max_bound[i]fori = 0, 1, 2(inclusive on both ends). Keep the surviving points in their original order, with all their channels. - Append
{"name": "CropBoundingBox", "remaining_points": <number of points kept>}to theapplied_transformslist.
RigidTransform, with params containing exactly target_frame and matrix.
target_frameis a non-empty string.matrixis a list of 4 rows, each a list of 4 finite numbers (not booleans). It is a 4x4 homogeneous matrixM. Do not check that it is a true rigid motion.- For each point with coordinates
(x, y, z), the new coordinates are the first three entries ofM · [x, y, z, 1]ᵀ. That is, new coordinateiisM[i][0]*x + M[i][1]*y + M[i][2]*z + M[i][3]*1.0. The fourth row ofMis ignored. Channels after the first three stay unchanged. - Set
metadata["frame_id"]totarget_frame, even if the key did not exist before. - Append
{"name": "RigidTransform"}to theapplied_transformslist.
Validation (all failures raise ValueError)
Validate everything before running any step, so a bad config never produces partial output.
pointsmust be a list,metadataa dict andconfiga list.- Every point must be a list with at least 3 entries. All points must have the same length. Every entry must be a finite
intorfloat(booleans, NaN and infinities are rejected). An emptypointslist is valid. - Every config item must be a dict whose keys are exactly
{"name", "params"}.namemust be a string andparamsa dict. - An unknown step name is an error.
- A step's
paramsmust have exactly the keys listed for it above, with the value rules given above.
Output
Return a dictionary {"points": ..., "metadata": ...}:
pointsis the processed list of points.metadatahas all the keys of the input metadata (withframe_idpossibly replaced), andapplied_transformsis the original list (or an empty list if absent) followed by the records from this run, in order.- The inputs must not be modified.
Constraints
0 <= len(points); each point has lengthD >= 3.- An empty scan runs cleanly through every step. Crop records
remaining_points: 0, and the rigid transform still updatesframe_id. - An empty
configlist is valid. The output is then a copy of the input scan, withapplied_transformscopied (or[]if it was absent).
Examples
Example 1
Input: process_lidar_scan([[0, 0, 0, 0.8], [20, 0, 0, 0.5], [-5, 5, 1, 0.2]], {'frame_id': 'lidar_top'}, [{'name': 'CropBoundingBox', 'params': {'min_bound': [-10, -10, -2], 'max_bound': [10, 10, 2]}}, {'name': 'RigidTransform', 'params': {'target_frame': 'vehicle', 'matrix': [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]}}])
Output: {'points': [[0, 0, 0, 0.8], [-5, 5, 1, 0.2]], 'metadata': {'frame_id': 'vehicle', 'applied_transforms': [{'name': 'CropBoundingBox', 'remaining_points': 2}, {'name': 'RigidTransform'}]}}
Example 2
Input: process_lidar_scan([], {'frame_id': 'lidar_top'}, [{'name': 'CropBoundingBox', 'params': {'min_bound': [-1, -1, -1], 'max_bound': [1, 1, 1]}}, {'name': 'RigidTransform', 'params': {'target_frame': 'vehicle', 'matrix': [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]}}])
Output: {'points': [], 'metadata': {'frame_id': 'vehicle', 'applied_transforms': [{'name': 'CropBoundingBox', 'remaining_points': 0}, {'name': 'RigidTransform'}]}}
Hints
Hint 1
Do all validation in a first pass that builds a list of parsed steps, and only then touch the points. This guarantees an invalid config raises before any work is done.
Hint 2
Copy the points rows and the metadata (including a fresh applied_transforms list) before processing so the caller's data is never mutated.
Hint 3
For the rigid step, only rows 0 to 2 of the 4x4 matrix matter. Compute each new coordinate as a dot product with (x, y, z, 1.0) and assign it back to the first three slots of the row, leaving extra channels alone.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The work splits into two phases: validate, then execute.
-
Validate everything first. Check the types of
points,metadataandconfig. Check that every point is a list of finite, non-boolean numbers of one common length of at least 3. Then walk the config. Each item must have exactly the keysnameandparams. Dispatch on the name:CropBoundingBoxmust have exactlymin_boundandmax_bound(3 finite numbers each, with min <= max per axis), andRigidTransformmust have exactlytarget_frame(non-empty string) andmatrix(4x4 of finite numbers). Any other name is unknown. Every problem raisesValueError. Each valid step is stored as a small tuple of its parsed parameters. -
Execute on copies. Copy every point row and the metadata dictionary. Give the copy its own
applied_transformslist, seeded from the input's list or an empty one. Then process the parsed steps in order:- Crop: keep rows where
lo[i] <= row[i] <= hi[i]for the first three axes, preserving order. Append a record with the number of survivors. - Rigid transform: for each row, build
(x, y, z, 1.0)and take the dot product with the first three rows of the matrix. Write the three results back into positions 0 to 2, so extra channels are untouched. Setframe_idand append a record.
- Crop: keep rows where
Why it is correct
- Validation completes before any step runs, so an invalid config can never yield a partially processed result.
- Cropping is a simple inclusive filter, and later steps see only the surviving points, so the recorded counts are right.
- Multiplying
Mby the homogeneous vector givesR·p + tfor the first three rows, which is the required rigid transform. Ignoring the fourth row matches the specification. - Copying rows, the metadata dictionary and the transform list means the inputs are never mutated.
- An empty scan simply produces empty loops, so crop reports 0 remaining points and the frame is still updated.
Complexity
Let N be the number of points, D the number of channels and T the number of steps.
- Time:
O(N·D)to validate the points,O(T)to validate the config, andO(T·N·D)to run it. The rigid transform uses a fixed 12 multiplications per point. - Space:
O(N·D)for the copied points, plusO(T)for the parsed steps and metadata.
Reference solution
from typing import Any, Dict, List
import math
def _is_num(v: Any) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
def process_lidar_scan(points: List[List[float]], metadata: Dict[str, Any], config: List[Dict[str, Any]]) -> Dict[str, Any]:
if not isinstance(points, list) or not isinstance(metadata, dict) or not isinstance(config, list):
raise ValueError("points, metadata, and config must be list, dict and list")
# ---- validate points ----
width = None
for row in points:
if not isinstance(row, list) or len(row) < 3:
raise ValueError("each point must be a list with at least three values")
if width is None:
width = len(row)
if len(row) != width or not all(_is_num(v) for v in row):
raise ValueError("points must share one length and hold finite numbers")
# ---- validate and parse config ----
steps = []
for item in config:
if (not isinstance(item, dict) or set(item) != {"name", "params"}
or not isinstance(item["name"], str) or not isinstance(item["params"], dict)):
raise ValueError("invalid step description")
name, params = item["name"], item["params"]
if name == "CropBoundingBox":
if set(params) != {"min_bound", "max_bound"}:
raise ValueError("CropBoundingBox needs min_bound and max_bound")
lo, hi = params["min_bound"], params["max_bound"]
if not isinstance(lo, list) or not isinstance(hi, list) or len(lo) != 3 or len(hi) != 3:
raise ValueError("bounds must have three entries")
if not all(_is_num(x) for x in lo + hi) or any(lo[i] > hi[i] for i in range(3)):
raise ValueError("bounds must be finite with min <= max")
steps.append((name, lo, hi))
elif name == "RigidTransform":
if set(params) != {"target_frame", "matrix"}:
raise ValueError("RigidTransform needs target_frame and matrix")
frame, matrix = params["target_frame"], params["matrix"]
if (not isinstance(frame, str) or not frame or not isinstance(matrix, list)
or len(matrix) != 4
or any(not isinstance(r, list) or len(r) != 4 for r in matrix)):
raise ValueError("bad target_frame or matrix shape")
if not all(_is_num(x) for r in matrix for x in r):
raise ValueError("matrix entries must be finite numbers")
steps.append((name, frame, matrix))
else:
raise ValueError("unknown transform: " + name)
# ---- run ----
out_points = [row[:] for row in points]
out_meta = dict(metadata)
out_meta["applied_transforms"] = list(metadata.get("applied_transforms", []))
for step in steps:
if step[0] == "CropBoundingBox":
_, lo, hi = step
out_points = [r for r in out_points
if all(lo[i] <= r[i] <= hi[i] for i in range(3))]
out_meta["applied_transforms"].append(
{"name": "CropBoundingBox", "remaining_points": len(out_points)})
else:
_, frame, m = step
for r in out_points:
vec = (r[0], r[1], r[2], 1.0)
r[:3] = [sum(m[i][j] * vec[j] for j in range(4)) for i in range(3)]
out_meta["frame_id"] = frame
out_meta["applied_transforms"].append({"name": "RigidTransform"})
return {"points": out_points, "metadata": out_meta}