Interview conceptCoding & Algorithms

Robust Coding And Numeric Edge Cases

Asked of: Data Scientist

Last updated

Top-to-bottom decision flowchart for robust numeric coding: validate inputs, choose analytic vs iterative solver (with bisect fallback), use Welford for streaming, handle NaN/empty, k-means reseed and spatial pruning.

What's being tested

These problems test numeric stability and robust handling of edge cases in algorithmic code: correct use of analytic vs iterative solvers, safe aggregation over missing/empty data, and cluster-maintenance strategies. Interviewers expect concise, production-ready code that handles NaNs, extreme values, degenerate geometry, and streaming inputs.

Patterns & templates

  • Pairwise quadratic solver for moving-object collisions — solve distance2(t)=r2distance^2(t)=r^2 as at2+bt+c=0at^2+bt+c=0, handle discriminant ≤0\le0, use math.isclose tolerances.

  • Use analytic formulas where stable; prefer math.fsum over sum for large numerics to avoid loss of precision.

  • Welford's algorithm for streaming mean/variance — single pass, O(1) memory, numerically stable incremental updates.

  • For empty/missing values, prefer numpy.nanmean or explicit checks with math.isnan/math.isfinite and return 0 or sentinel per spec.

  • Root-finding fallbacks: use bisect (guaranteed convergence) when Newton's method diverges; always cap iterations and check derivative magnitude.

  • K-means empty-cluster handling: re-seed with farthest point, split largest cluster, or use minibatch to avoid empties; document deterministic tie-breaks.

  • Spatial pruning: use grid hashing / KD-tree / sweep-line to reduce O(n2)O(n^2) pair checks to near-linear in sparse scenarios.

  • Use relative vs absolute tolerance: compare with abs(a−b)≤max(rel_tol⋅max(∣a∣,∣b∣),abs_tol)abs(a-b) \le max(rel\_tol \cdot max(|a|,|b|), abs\_tol) (implement via math.isclose).

Common pitfalls

Pitfall: Treating NaN or infinite values as numbers — forgetting math.isfinite leads to silent wrong answers or crashes.

Pitfall: Using naive sum for long lists — leads to catastrophic cancellation; prefer math.fsum or compensated summation.

Pitfall: Returning any root from quadratic without checking time bounds or negative times — report earliest non-negative collision only.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts