Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Both moving people travel at the same speed toward the stationary third person. Their arrival order therefore depends only on their distances to the target, regardless of which side they start on.
Approach
Compute the first person's distance as abs(x - z) and the second person's distance as abs(y - z). Return one if the first distance is smaller, two if the second distance is smaller, and zero if they are equal.
Absolute differences measure distance on the number line without introducing direction into the comparison. Equal distances mean simultaneous arrival, including when the two people start on opposite sides of the target. The calculation requires only the three positions and does not need to simulate movement.
class Solution:
def findClosest(self, x: int, y: int, z: int) -> int:
d1 = abs(x - z)
d2 = abs(y - z)
if d1 < d2:
return 1
elif d2 < d1:
return 2
else:
return 0Complexity analysis
Time: O(1). Auxiliary space: O(1).
