3516. Find Closest Person
UnknownView on LeetCode
Time: O(1)
Space: O(1)
Problem Overview
Find Closest Person (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Simulation pattern in coding interviews. Return the value in {x, y} with smaller |v - z|; tie-break to smaller value.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Return the value in {x, y} with smaller |v - z|; tie-break to smaller value.
Related patterns: Array, Simulation
3516.cs
C#
// Approach: Return the value in {x, y} with smaller |v - z|; tie-break to smaller value.
// Time: O(1) Space: O(1)
public class Solution
{
public int FindClosest(int x, int y, int z)
{
// Calculate absolute distance from x to z
int distanceFromXToZ = Math.Abs(x - z);
// Calculate absolute distance from y to z
int distanceFromYToZ = Math.Abs(y - z);
// Compare distances and return appropriate result
if (distanceFromXToZ == distanceFromYToZ)
return 0; // Both x and y are equidistant from z
else if (distanceFromXToZ < distanceFromYToZ)
return 1; // x is closer to z
else
return 2; // y is closer to z
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)