Company: DevRev
Difficulty: medium
Find Closest Element Problem Description Given a sorted array of integers a , your task is to determine which element of a is closest to all other values of a . In other words, find the element x in a , which minimizes the following sum: abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[n-1] - x) (where abs denotes the absolute value) If there are several possible answers, output the smallest one. Examples Example 1: Input: a = [2, 4, 7] Output: 4 Explanation: We need to find an element x from a that minimizes the sum of absolute differences. Let's calculate the sum for each possible x in a : For x = 2 , the value will be abs(2 - 2) + abs(4 - 2) + abs(7 - 2) = 0 + 2 + 5 = 7 . For x = 4 , the value will be abs(2 - 4) + abs(4 - 4) + abs(7 - 4) = 2 + 0 + 3 = 5 . For x = 7 , the value will be abs(2 - 7) + abs(4 - 7) + abs(7 - 7) = 5 + 3 + 0 = 8 . The minimum sum is 5, which is achieved when x = 4 . Therefore, the output is 4.