Beautiful Pairs Problem
Description
LeetCode Problem 2613.
You are given two 0-indexed integer arrays nums1 and nums2 of the same length. A pair of indices (i,j) is called beautiful if|nums1[i] - nums1[j]| + |nums2[i] - nums2[j]| is the smallest amongst all possible indices pairs where i < j.
Return the beautiful pair. In the case that there are multiple beautiful pairs, return the lexicographically smallest pair.
Note that
|x|denotes the absolute value ofx.- A pair of indices
(i_1, j_1)is lexicographically smaller than(i_2, j_2)ifi_1 < i_2ori_1 == i_2andj_1 < j_2.
Example 1:
Input: nums1 = [1,2,3,2,4], nums2 = [2,3,1,2,3]
Output: [0,3]
Explanation: Consider index 0 and index 3. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve.
Example 2:
Input: nums1 = [1,2,4,3,2,5], nums2 = [1,4,2,3,5,1]
Output: [1,4]
Explanation: Consider index 1 and index 4. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve.
Constraints:
2 <= nums1.length, nums2.length <= 10^5nums1.length == nums2.length0 <= nums1_i<= nums1.length0 <= nums2_i <= nums2.length
Solution
Approach: Sort by x + Divide and Conquer
The task is to find the closest pair of points under Manhattan distance, preferring the smallest index pair on ties.
First handle repeated points: if some point appears more than once, the distance is 0. Scanning indices in order, the first index i whose point repeats gives the answer [i, j], where j is the next index with that point.
Otherwise all points are distinct. Sort them by x and solve each range [l, r] recursively:
- Solve the left half and the right half, and keep the better result (smaller distance, then smaller indices). Call its distance
d. - A closer pair may straddle the middle. Only points whose
xis withindof the middle point'sxcan take part, so collect those and sort them byy. - Compare each point with the following ones in
yorder and stop as soon as theygap exceedsd, since the distance can only be larger from there. Update the best pair whenever a smaller distance (or equal distance with smaller indices) is found.
Because the points are distinct and d is the best distance in each half, only a constant number of points fall inside each strip window, so the straddling step is cheap.
Complexity: O(n log n) time (a log factor more for the repeated sorting by y) and O(n) space, where n is the length of the arrays.
from collections import defaultdict
from math import inf
class Solution:
def beautifulPair(self, nums1: List[int], nums2: List[int]) -> List[int]:
def dist(x1: int, y1: int, x2: int, y2: int) -> int:
return abs(x1 - x2) + abs(y1 - y2)
def dfs(l: int, r: int):
if l >= r:
return inf, -1, -1
m = (l + r) >> 1
x = points[m][0]
d1, pi1, pj1 = dfs(l, m)
d2, pi2, pj2 = dfs(m + 1, r)
if d1 > d2 or (d1 == d2 and (pi1 > pi2 or (pi1 == pi2 and pj1 > pj2))):
d1, pi1, pj1 = d2, pi2, pj2
t = [p for p in points[l : r + 1] if abs(p[0] - x) <= d1]
t.sort(key=lambda x: x[1])
for i in range(len(t)):
for j in range(i + 1, len(t)):
if t[j][1] - t[i][1] > d1:
break
pi, pj = sorted([t[i][2], t[j][2]])
d = dist(t[i][0], t[i][1], t[j][0], t[j][1])
if d < d1 or (d == d1 and (pi < pi1 or (pi == pi1 and pj < pj1))):
d1, pi1, pj1 = d, pi, pj
return d1, pi1, pj1
pl = defaultdict(list)
for i, (x, y) in enumerate(zip(nums1, nums2)):
pl[(x, y)].append(i)
points = []
for i, (x, y) in enumerate(zip(nums1, nums2)):
if len(pl[(x, y)]) > 1:
return [i, pl[(x, y)][1]]
points.append((x, y, i))
points.sort()
_, pi, pj = dfs(0, len(points) - 1)
return [pi, pj]