Facebook Pixel

3516. Find Closest Person

Problem Description

You are given three integers x, y, and z representing 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)

Person 1 and Person 2 both move toward Person 3 at the same speed. Your task is to determine which person reaches Person 3 first.

Return:

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

Since both people move at the same speed, the person who is initially closer to Person 3 will arrive first. The solution calculates the absolute distance between each moving person and Person 3:

  • Distance a = |x - z| for Person 1
  • Distance b = |y - z| for Person 2

Then it compares these distances to determine who arrives first. If the distances are equal, both arrive simultaneously.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is that when two people move toward a fixed target at the same speed, the outcome depends entirely on their initial distances from the target. Think of it like a race where two runners start at different positions but run at identical speeds toward the same finish line - the runner who starts closer will always win.

Since Person 3 is stationary and both Person 1 and Person 2 move at the same speed, we don't need to calculate actual movement or time. We only need to compare their starting distances from Person 3.

The distance calculation uses absolute values |x - z| and |y - z| because people can be positioned on either side of Person 3 on the number line. Whether Person 1 is at position 5 and Person 3 is at position 10 (distance = 5), or Person 1 is at position 15 and Person 3 is at position 10 (distance = 5), the time to reach Person 3 remains the same.

By comparing these absolute distances:

  • If |x - z| < |y - z|, Person 1 is closer and arrives first
  • If |x - z| > |y - z|, Person 2 is closer and arrives first
  • If |x - z| = |y - z|, they're equidistant and arrive together

This transforms a seemingly dynamic problem about movement into a simple static comparison of initial distances.

Learn more about Math patterns.

Solution Approach

The implementation follows a straightforward mathematical approach:

  1. Calculate distances: First, we compute the absolute distance between each moving person and Person 3:

    • a = abs(x - z) gives the distance from Person 1 to Person 3
    • b = abs(y - z) gives the distance from Person 2 to Person 3
  2. Compare and return: We then compare these distances using a conditional expression:

    • If a == b, both distances are equal, so we return 0 (both arrive simultaneously)
    • If a < b, Person 1 is closer and arrives first, so we return 1
    • Otherwise (a > b), Person 2 is closer and arrives first, so we return 2

The solution uses a compact ternary operator chain to handle all three cases in a single return statement: return 0 if a == b else (1 if a < b else 2).

This approach has a time complexity of O(1) since we only perform a constant number of arithmetic operations and comparisons. The space complexity is also O(1) as we only use two additional variables to store the distances.

The beauty of this solution lies in its simplicity - by recognizing that equal speeds mean we only need to compare initial distances, we avoid any complex calculations involving speed, time, or movement simulation.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a concrete example to illustrate the solution approach.

Example: Suppose we have:

  • Person 1 at position x = 2
  • Person 2 at position y = 7
  • Person 3 at position z = 5

Visualizing this on a number line:

0---1---2---3---4---5---6---7---8
        P1          P3      P2

Step 1: Calculate distances

First, we calculate the absolute distance from each moving person to Person 3:

  • Distance from Person 1 to Person 3: a = |2 - 5| = |-3| = 3
  • Distance from Person 2 to Person 3: b = |7 - 5| = |2| = 2

Step 2: Compare distances

Now we compare the distances:

  • Is a == b? No, 3 ≠ 2, so they don't arrive at the same time
  • Is a < b? No, 3 > 2, so Person 1 is not closer
  • Since a > b (3 > 2), Person 2 is closer to Person 3

Step 3: Return result

Since Person 2 has a shorter distance to travel (2 units vs 3 units) and both people move at the same speed, Person 2 will reach Person 3 first. We return 2.

To verify our logic: if both people move at 1 unit per time:

  • Person 2 reaches Person 3 in 2 time units
  • Person 1 reaches Person 3 in 3 time units
  • Person 2 arrives first ✓

Solution Implementation

1class Solution:
2    def findClosest(self, x: int, y: int, z: int) -> int:
3        """
4        Determines which of two numbers (x or y) is closest to a target number z.
5      
6        Args:
7            x: First number to compare
8            y: Second number to compare  
9            z: Target number to measure distance from
10          
11        Returns:
12            0 if x and y are equidistant from z
13            1 if x is closer to z than y
14            2 if y is closer to z than x
15        """
16        # Calculate absolute distance from x to z
17        distance_x_to_z = abs(x - z)
18      
19        # Calculate absolute distance from y to z
20        distance_y_to_z = abs(y - z)
21      
22        # Compare distances and return appropriate value
23        if distance_x_to_z == distance_y_to_z:
24            return 0  # Both are equidistant
25        elif distance_x_to_z < distance_y_to_z:
26            return 1  # x is closer
27        else:
28            return 2  # y is closer
29
1class Solution {
2    /**
3     * Finds which of two numbers (x or y) is closest to a target number z.
4     * 
5     * @param x First number to compare
6     * @param y Second number to compare  
7     * @param z Target number to measure distance from
8     * @return 0 if x and y are equidistant from z,
9     *         1 if x is closer to z,
10     *         2 if y is closer to z
11     */
12    public int findClosest(int x, int y, int z) {
13        // Calculate absolute distance from x to z
14        int distanceFromXToZ = Math.abs(x - z);
15      
16        // Calculate absolute distance from y to z
17        int distanceFromYToZ = Math.abs(y - z);
18      
19        // Compare distances and return appropriate result
20        if (distanceFromXToZ == distanceFromYToZ) {
21            return 0;  // Both x and y are equidistant from z
22        } else if (distanceFromXToZ < distanceFromYToZ) {
23            return 1;  // x is closer to z
24        } else {
25            return 2;  // y is closer to z
26        }
27    }
28}
29
1class Solution {
2public:
3    /**
4     * Determines which of two numbers (x or y) is closer to a target value z.
5     * 
6     * @param x First number to compare
7     * @param y Second number to compare  
8     * @param z Target value to measure distance from
9     * @return 0 if x and y are equidistant from z,
10     *         1 if x is closer to z,
11     *         2 if y is closer to z
12     */
13    int findClosest(int x, int y, int z) {
14        // Calculate absolute distance from x to z
15        int distanceFromX = abs(x - z);
16      
17        // Calculate absolute distance from y to z
18        int distanceFromY = abs(y - z);
19      
20        // Compare distances and return appropriate result
21        if (distanceFromX == distanceFromY) {
22            return 0;  // Both are equidistant
23        } else if (distanceFromX < distanceFromY) {
24            return 1;  // x is closer
25        } else {
26            return 2;  // y is closer
27        }
28    }
29};
30
1/**
2 * Finds which of two numbers (x or y) is closest to a target number z
3 * @param x - First number to compare
4 * @param y - Second number to compare  
5 * @param z - Target number to find the closest value to
6 * @returns 0 if x and y are equidistant from z, 1 if x is closer, 2 if y is closer
7 */
8function findClosest(x: number, y: number, z: number): number {
9    // Calculate absolute distance from x to z
10    const distanceFromX: number = Math.abs(x - z);
11  
12    // Calculate absolute distance from y to z
13    const distanceFromY: number = Math.abs(y - z);
14  
15    // Compare distances and return appropriate result
16    // If distances are equal, return 0
17    // If x is closer (smaller distance), return 1
18    // If y is closer (smaller distance), return 2
19    return distanceFromX === distanceFromY ? 0 : distanceFromX < distanceFromY ? 1 : 2;
20}
21

Time and Space Complexity

The time complexity is O(1) because the function performs a fixed number of operations regardless of the input size. It calculates two absolute differences (abs(x - z) and abs(y - z)), performs one comparison (a == b), and potentially one more comparison (a < b), all of which are constant-time operations.

The space complexity is O(1) because the function only uses a fixed amount of extra space to store two variables a and b, regardless of the input values. No additional data structures that scale with input size are created.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Integer Overflow in Distance Calculation

While Python handles arbitrary precision integers automatically, in other languages like Java or C++, calculating abs(x - z) could cause integer overflow when x and z are at opposite extremes of the integer range (e.g., x = INT_MAX and z = INT_MIN).

Solution: In languages with fixed integer sizes, use safe distance calculation methods:

# Python handles this automatically, but in other languages:
# Instead of: abs(x - z)
# Use: abs((long)x - (long)z) or check for overflow conditions

2. Assuming Positions are Always Positive

A common mistake is mentally assuming all positions are positive numbers and potentially writing logic that doesn't account for negative positions or mixed signs.

Solution: The current implementation correctly uses abs() which handles all cases:

  • Both positions positive: abs(5 - 3) = 2
  • Both positions negative: abs(-5 - (-3)) = 2
  • Mixed signs: abs(-5 - 3) = 8

3. Misunderstanding the Return Values

Developers might confuse the return values, especially returning the actual person who is closer rather than the index/identifier (1 or 2).

Solution: Add clear documentation and consider using an enum or named constants:

class Solution:
    BOTH_ARRIVE_SAME = 0
    PERSON_1_FIRST = 1
    PERSON_2_FIRST = 2
  
    def findClosest(self, x: int, y: int, z: int) -> int:
        distance_x_to_z = abs(x - z)
        distance_y_to_z = abs(y - z)
      
        if distance_x_to_z == distance_y_to_z:
            return self.BOTH_ARRIVE_SAME
        elif distance_x_to_z < distance_y_to_z:
            return self.PERSON_1_FIRST
        else:
            return self.PERSON_2_FIRST

4. Floating Point Precision Issues

If the problem were extended to handle floating-point positions, direct equality comparison (==) could fail due to precision errors.

Solution: For floating-point comparisons, use an epsilon value:

def findClosest(self, x: float, y: float, z: float) -> int:
    EPSILON = 1e-9
    distance_x_to_z = abs(x - z)
    distance_y_to_z = abs(y - z)
  
    if abs(distance_x_to_z - distance_y_to_z) < EPSILON:
        return 0  # Distances are effectively equal
    elif distance_x_to_z < distance_y_to_z:
        return 1
    else:
        return 2
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

What are the two properties the problem needs to have for dynamic programming to be applicable? (Select 2)


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More