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: Find Closest Points in Manhattan DistanceInput Arraysnums1 = [1,3,2]nums2 = [1,2,3]Manhattan Distance|x₁-x₂| + |y₁-y₂|for all pairs (i,j)Beautiful PairMinimum distance = 2Indices: [1,2](1,1) idx=0(3,2) idx=1(2,3) idx=2Distance = |3-2| + |2-3| = 2Output: [1,2]
Understanding the Visualization
1
Input
Two arrays representing points in 2D space
2
Calculate
Find Manhattan distance for each pair
3
Output
Return lexicographically smallest minimum pair
Key Takeaway
🎯 Key Insight: This is a closest pair problem using Manhattan distance in 2D space
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