Leetcode #1855: Maximum Distance Between a Pair of Values
In this guide, we solve Leetcode #1855 Maximum Distance Between a Pair of Values in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given two non-increasing 0-indexed integer arrays nums1 and nums2. A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j].
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Two Pointers, Binary Search
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
Output: 2
Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
The maximum distance is 2 with pair (2,4).
Python Solution
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
ans = 0
nums2 = nums2[::-1]
for i, v in enumerate(nums1):
j = len(nums2) - bisect_left(nums2, v) - 1
ans = max(ans, j - i)
return ans
Complexity
The time complexity is , where and are the lengths of and respectively. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.