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:

  • 1 if Person 1 reaches Person 3 first
  • 2 if Person 2 reaches Person 3 first
  • 0 if 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
Find Closest Person - Visual SolutionPositionPerson 1x = 1Person 2y = 4Person 3 (Target)z = 3Distance = |1-3| = 2Distance = |4-3| = 1Result: Person 2 wins!Since 1 < 2, Person 2 has shorter distanceReturn: 2๐Ÿ’ก Key Insight: Equal speed means winner is determined by initial distance only!
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!
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
23.5K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen