Find Closest Person - Problem
Imagine three people standing on a number line: Person 1 at position x, Person 2 at position y, and Person 3 (the target) at position z.
Person 3 stays put while Person 1 and Person 2 both start moving toward Person 3 at exactly the same speed. Your task is to determine who will reach Person 3 first!
Input: Three integers x, y, and z representing the positions on a number line.
Output: Return an integer based on who arrives first:
1if Person 1 reaches Person 3 first2if Person 2 reaches Person 3 first0if both arrive at the same time
Example: If Person 1 is at position 1, Person 2 is at position 4, and Person 3 is at position 3, then Person 1 needs to travel distance 2 while Person 2 needs to travel distance 1. Since they move at the same speed, Person 2 arrives first!
Input & Output
example_1.py โ Basic case
$
Input:
x = 1, y = 4, z = 3
โบ
Output:
2
๐ก Note:
Person 1 needs to travel distance |1-3| = 2, Person 2 needs to travel distance |4-3| = 1. Person 2 has the shorter distance, so Person 2 arrives first.
example_2.py โ Tie case
$
Input:
x = 2, y = 8, z = 5
โบ
Output:
0
๐ก Note:
Person 1 needs to travel distance |2-5| = 3, Person 2 needs to travel distance |8-5| = 3. Both have equal distances, so they arrive at the same time.
example_3.py โ Person 1 wins
$
Input:
x = 10, y = 1, z = 7
โบ
Output:
1
๐ก Note:
Person 1 needs to travel distance |10-7| = 3, Person 2 needs to travel distance |1-7| = 6. Person 1 has the shorter distance, so Person 1 arrives first.
Constraints
- -109 โค x, y, z โค 109
- All inputs are integers
- Positions can be negative, zero, or positive
Visualization
Tap to expand
Understanding the Visualization
1
Setup Positions
Place Person 1 at x, Person 2 at y, and Person 3 (target) at z on the number line
2
Calculate Distances
Measure how far each person needs to travel: |x-z| and |y-z|
3
Determine Winner
Since they move at equal speed, whoever has shorter distance wins the race
Key Takeaway
๐ฏ Key Insight: When two objects move at the same speed toward a target, the one starting closer will always arrive first - no complex algorithms needed, just simple distance comparison!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code