Sobes.tech
Junior — Senior

Removing the first surname whose length is closest to the median value

livecode

Task condition

Given an array of strings, each representing a person's full name. It is necessary to determine the median length of surnames in the entire array and delete the first record for which the difference between the length of the surname and the found median is minimal.

Initial array: ["Tabachnik Yan Efimovich", "Cheremisinov Mikhail Denisovich", "Babinets Rinat Germanovich", "Zhebrakov Ivan Maksimovich", "Perfiriev Ruslan Konstantinovich", "Mukankin Vitaliy Vadimovich", "Tzizin Rinat Valentinovich", "Tinaev Vitaliy Viktorovich"]

Algorithm:

  1. For each string, extract the surname (the first part before the first space).
  2. Count the length of each surname.
  3. Sort the obtained lengths and find the median (if the number is even — take the average of the two central values).
  4. Iterate through the array in the original order and calculate the absolute difference between the length of the current surname and the median.
  5. Record the element with the minimal difference and delete it from the array.

The result should be a collection without the found element.

Example implementation in Python (can be adapted to any language):

names = [
    "Tabachnik Yan Efimovich",
    "Cheremisinov Mikhail Denisovich",
    "Babinets Rinat Germanovich",
    "Zhebrakov Ivan Maksimovich",
    "Perfiriev Ruslan Konstantinovich",
    "Mukankin Vitaliy Vadimovich",
    "Tzizin Rinat Valentinovich",
    "Tinaev Vitaliy Viktorovich",
]

# steps 1-3
surnames = [full.split()[0] for full in names]
lengths = [len(s) for s in surnames]
sorted_lengths = sorted(lengths)
mid = len(sorted_lengths) // 2
if len(sorted_lengths) % 2:
    median = sorted_lengths[mid]
else:
    median = (sorted_lengths[mid - 1] + sorted_lengths[mid]) / 2

# steps 4-5
best_idx = None
best_diff = float('inf')
for i, s in enumerate(surnames):
    diff = abs(len(s) - median)
    if diff < best_diff:
        best_diff = diff
        best_idx = i

if best_idx is not None:
    del names[best_idx]

print(names)