Dashboard Temp Share Shortlinks Frames API

HTMLify

Find the closest pair from two arrays
Views: 4 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
    def findClosestPair(self, arr1, arr2, x):
        n = len(arr1)
        m = len(arr2)
        
        # Initializing pointers
        left = 0
        right = m - 1
        
        min_diff = float('inf')
        res_pair = [0, 0]
        
        while left < n and right >= 0:
            current_sum = arr1[left] + arr2[right]
            current_diff = abs(current_sum - x)
            
            # Update result if a closer sum is found
            if current_diff < min_diff:
                min_diff = current_diff
                res_pair = [arr1[left], arr2[right]]
            
            # Adjust pointers based on current_sum
            if current_sum > x:
                right -= 1
            elif current_sum < x:
                left += 1
            else:
                # Exact match found
                return [arr1[left], arr2[right]]
                
        return res_pair