Problem statement

https://binarysearch.com/problems/Minimize-Absolute-Difference-of-Three-Numbers/

Solution

Let us fix element in array B and then look for closest elements in A and C, using binary search.

Complexity

It is O(n log n), where n = max(len(A), len(B), len(C)) for time and O(n) for space.

Code

class Solution:
    def solve(self, A, B, C):
        A, C, ans = sorted(A), sorted(C), float("inf")
        for x in B:
            p1, p2 = float("inf"), float("inf")
            i1 = bisect.bisect(A, x)
            if i1 < len(A): p1 = min(p1, A[i1] - x)
            if i1 > 0: p1 = min(p1, x - A[i1-1])
            i2 = bisect.bisect(C, x)
            if i2 < len(C): p2 = min(p2, C[i2] - x)
            if i2 > 0: p2 = min(p2, x - C[i2-1])
            ans = min(ans, p1 + p2)
        return ans