DDSA Solutions

3516. Find Closest Person

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