#3516

Find Closest Person

Easy
MathMathAbsolute Difference
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Directly compute distances and compare them in constant time, ensuring efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate distance from Person 1 to Person 3: |x - z|.
  2. 2Step 2: Calculate distance from Person 2 to Person 3: |y - z|.
  3. 3Step 3: Compare the distances and return the result based on who is closer.
solution.py9 lines
1def find_closest_person(x, y, z):
2    dist1 = abs(x - z)
3    dist2 = abs(y - z)
4    if dist1 < dist2:
5        return 1
6    elif dist2 < dist1:
7        return 2
8    else:
9        return 0

Complexity note: Both time and space complexities are constant since we only perform a fixed number of calculations.

  • 1Distance comparison is the key to solving the problem.
  • 2Both persons move at the same speed, simplifying the logic.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.