distance functions with early termination conditions