The Nearest Value Mapper

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L5
Asked in
Amazon

Problem

Given keys (list of integers) and values (list of integers), return a dict mapping each key to the value whose numeric distance is smallest. Distance is abs(key - value). When a key is equidistant from two values, break the tie by choosing the smaller value. Duplicate keys are allowed; the last occurrence wins. The returned dict uses STRING keys (e.g. key 5 becomes "5") for JSON compatibility in the test harness, with the chosen integer value.

Close enough counts. Ties go low.

Example 1

Input:

keys = [1,5,12], values = [3,7,10]

Output:

{"1":3,"5":3,"12":10}

Example 2

Input:

keys = [4], values = [1,7]

Output:

{"4":1}

Worked solution and explanation

Why this problem exists in real interviews

This tests approximate matching with a deterministic tie-break, a common operation in data engineering when joining datasets on non-exact keys (e.g., aligning a query to the nearest reference value). It checks whether candidates can track a running best while applying a precise, well-specified tie-breaking rule.


Break down the requirements

Step 1: Define the distance metric

Distance between a key and a value is abs(key - value). For each key you want the value that minimizes this distance.

Step 2: Track the best match with a tie-break

For each key, iterate over all values and keep a running best. Update the best when a value has a strictly smaller distance, OR an equal distance but a smaller value (the tie-break).

Step 3: Assemble the output with string keys

Build the result dict with the key converted to a string (str(key)) mapped to the chosen value. Iterating keys in order means a duplicate key is naturally overwritten by its last occurrence.


The solution

Running best with smaller-value tie-break
def closest_mapping(keys, values):
    result = {}
    for key in keys:
        best_value = None
        best_distance = None
        for value in values:
            distance = abs(key - value)
            if (
                best_value is None
                or distance < best_distance
                or (distance == best_distance and value < best_value)
            ):
                best_value = value
                best_distance = distance
        result[str(key)] = best_value
    return result

Common follow-up questions