Find Closest Person (LeetCode 3516): Solution and Explanation
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
- Compute
d1 = |x - z|andd2 = |y - z|. - If
d1 < d2, return 1. - If
d2 < d1, return 2. - Otherwise return 0.
Step-by-step example
x = 2, y = 7, z = 4
- d1 = |2 - 4| = 2.
- d2 = |7 - 4| = 3.
- 2 < 3, so person 1 reaches person 3 first.
- 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 01class Solution {
2 public int findClosest(int x, int y, int z) {
3 int d1 = Math.abs(x - z);
4 int d2 = Math.abs(y - z);
5 if (d1 < d2) {
6 return 1;
7 }
8 if (d2 < d1) {
9 return 2;
10 }
11 return 0;
12 }
13}1class Solution {
2public:
3 int findClosest(int x, int y, int z) {
4 int d1 = abs(x - z);
5 int d2 = abs(y - z);
6 if (d1 < d2) {
7 return 1;
8 }
9 if (d2 < d1) {
10 return 2;
11 }
12 return 0;
13 }
14};Time and space complexity
O(1)
Two subtractions, two absolute values and at most two comparisons.
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.