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 of x.

A pair of indices (i1, j1) is lexicographically smaller than (i2, j2) if i1 < i2 or i1 == i2 and j1 < j2.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,3,2], nums2 = [1,2,3]
Output: [1,2]
💡 Note: Check all pairs: (0,1) has distance |1-3| + |1-2| = 3, (0,2) has distance |1-2| + |1-3| = 3, (1,2) has distance |3-2| + |2-3| = 2. The minimum distance is 2 at indices (1,2).
Example 2 — Multiple Minimum Pairs
$ Input: nums1 = [1,1,1,1], nums2 = [1,1,1,1]
Output: [0,1]
💡 Note: All points are identical, so all pairs have distance 0. Return the lexicographically smallest pair (0,1).
Example 3 — Negative Numbers
$ Input: nums1 = [-1,2], nums2 = [1,-1]
Output: [0,1]
💡 Note: Only one pair (0,1) with distance |-1-2| + |1-(-1)| = 3 + 2 = 5.

Constraints

  • 2 ≤ nums1.length == nums2.length ≤ 105
  • -104 ≤ nums1[i], nums2[i] ≤ 104

Visualization

Tap to expand
Beautiful Pairs - Sort and Sweep INPUT nums1 = [1, 3, 2] 1 i=0 3 i=1 2 i=2 nums2 = [1, 2, 3] 1 i=0 2 i=1 3 i=2 Points: (x, y) P0: (1, 1) P1: (3, 2) P2: (2, 3) Manhattan distance = |x1-x2| + |y1-y2| ALGORITHM STEPS 1 Transform Coords x' = x + y, y' = x - y 2 Sort by x' Keep original indices 3 Sweep Line Check nearby points 4 Track Min Distance Update best pair Distance Calculations: (0,1): |1-3|+|1-2| = 3 (0,2): |1-2|+|1-3| = 3 (1,2): |3-2|+|2-3| = 2 [MIN] Smallest = (1,2) with dist 2 FINAL RESULT Beautiful Pair Found: x y P0(1,1) P1(3,2) P2(2,3) Output: [1, 2] OK - Verified Min Manhattan dist = 2 Key Insight: The Manhattan distance |x1-x2| + |y1-y2| can be transformed using coordinate rotation: x' = x + y, y' = x - y. This converts Manhattan to Chebyshev distance: max(|x1'-x2'|, |y1'-y2'|). Sort by x', then sweep with a balanced tree on y' to find nearest neighbors efficiently in O(n log n). TutorialsPoint - Beautiful Pairs | Sort and Sweep Approach
Asked in
Google 45 Facebook 32 Amazon 28
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen