DDSA Solutions

3516. Find Closest Person

Time: O(1)
Space: O(1)
Advertisement

Approach

Return the value in {x, y} with smaller |v - z|; tie-break to smaller value.

Key Techniques

Array

Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.

Simulation

Simulation problems require implementing the described process step by step. Focus on correctly handling edge cases and state transitions. Common in geometry, game problems, and string manipulation. Optimize only if the naive simulation exceeds the time limit.

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
    }
}
Advertisement
Was this solution helpful?