Find Closest Person - Problem

You are given three integers x, y, and z, representing the positions of three people on a number line:

  • x is the position of Person 1
  • y is the position of Person 2
  • z is the position of Person 3, who does not move

Both Person 1 and Person 2 move toward Person 3 at the same speed. Determine which person reaches Person 3 first:

  • Return 1 if Person 1 arrives first
  • Return 2 if Person 2 arrives first
  • Return 0 if both arrive at the same time

Input & Output

Example 1 — Person 2 Closer
$ Input: x = 1, y = 4, z = 3
Output: 2
💡 Note: Distance from Person 1 to Person 3: |1-3| = 2. Distance from Person 2 to Person 3: |4-3| = 1. Person 2 is closer, so return 2.
Example 2 — Equal Distance
$ Input: x = 2, y = 6, z = 4
Output: 0
💡 Note: Distance from Person 1 to Person 3: |2-4| = 2. Distance from Person 2 to Person 3: |6-4| = 2. Both distances are equal, so return 0.
Example 3 — Person 1 Closer
$ Input: x = 10, y = 2, z = 8
Output: 1
💡 Note: Distance from Person 1 to Person 3: |10-8| = 2. Distance from Person 2 to Person 3: |2-8| = 6. Person 1 is closer, so return 1.

Constraints

  • -109 ≤ x, y, z ≤ 109
  • All positions can be anywhere on the number line

Visualization

Tap to expand
Find Closest Person - Optimal Solution INPUT 0 1 2 3 4 5 P1 P2 P3 x = 1 y = 4 z = 3 P1, P2 move toward P3 at same speed P3 is stationary ALGORITHM STEPS 1 Calculate Distance 1 dist1 = |x - z| = |1-3| = 2 2 Calculate Distance 2 dist2 = |y - z| = |4-3| = 1 3 Compare Distances dist1=2 vs dist2=1 4 Determine Winner dist2 < dist1 Person 2 is closer! 1 < 2 --> Return 2 FINAL RESULT z=3 P2 P1 Winner: P2 Output 2 OK - Person 2 arrives first! P1: 2 units away P2: 1 unit away Key Insight: Since both persons move at the same speed, the one closer to the target (Person 3) will arrive first. Compare absolute distances: |x-z| vs |y-z|. Return 1 if dist1<dist2, return 2 if dist2<dist1, return 0 if equal. TutorialsPoint - Find Closest Person | Optimal Solution
Asked in
Google 15 Microsoft 12
12.0K Views
Medium Frequency
~5 min Avg. Time
450 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