Find Closest Person (LeetCode 3516): Solution and Explanation

Easy
Math

Two people walk at the same speed toward a third person on a number line. Return which one arrives first, or 0 for a tie.

Intuition

When two walkers move at the same speed, the one with less ground to cover always arrives first. The race is decided before anyone moves.

On a number line the ground to cover is the absolute difference of positions: |x - z| for person 1 and |y - z| for person 2.

So the whole problem is one comparison between two distances, with a separate answer when they are equal.

Approach: Compare absolute distances

  1. Compute d1 = |x - z| and d2 = |y - z|.
  2. If d1 < d2, return 1.
  3. If d2 < d1, return 2.
  4. Otherwise return 0.

Step-by-step example

x = 2, y = 7, z = 4
  1. d1 = |2 - 4| = 2.
  2. d2 = |7 - 4| = 3.
  3. 2 < 3, so person 1 reaches person 3 first.
  4. Return 1.

Code: Python, Java, C++

1class Solution:
2    def findClosest(self, x: int, y: int, z: int) -> int:
3        d1 = abs(x - z)
4        d2 = abs(y - z)
5        if d1 < d2:
6            return 1
7        if d2 < d1:
8            return 2
9        return 0
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1)

Two subtractions, two absolute values and at most two comparisons.

Space

O(1)

Only the two distances are stored.

Other approaches

Simulate the walk (time O(|x - z| + |y - z|), space O(1))

Move both people one unit toward z per tick and see who lands on z first. It matches the story but takes up to 99 ticks for the same answer.

Sign of the difference (time O(1), space O(1))

Compute d = |x - z| - |y - z| and map negative to 1, positive to 2 and zero to 0. Same logic in a single expression.

Common mistakes

  • Forgetting the absolute value. Person 1 can stand on either side of person 3.
  • Returning 1 or 2 for a tie. Equal distances must return 0.
  • Mixing up the return codes: 1 means person 1 is closer, 2 means person 2 is closer.

Frequently asked questions

Does the direction of walking matter?

No. Each person walks straight toward z, so only the distance |position - z| matters.

What if a person already stands on z?

That distance is 0, so that person wins unless the other one is also at z, which is a tie.

Why not simulate the walk?

It works, but equal speeds mean arrival time is proportional to distance, so comparing distances gives the answer directly.