Maximum Distance Between a Pair of Values — LeetCode 1855 Python Solution

MediumArrayTwo PointersBinary Search
Problem
#1855
Reading time
2 min

The problem

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].

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).

Python solution

Python
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

MeasureComplexity
TimeO(m \times \log n), where m and n are the lengths of nums1 and nums2 respectively
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1855. Maximum Distance Between a Pair of Values is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1855. Maximum Distance Between a Pair of Values?
LeetCode 1855. Maximum Distance Between a Pair of Values is rated Medium on LeetCode.
What is the time complexity of LeetCode 1855. Maximum Distance Between a Pair of Values?
The Python solution on this page runs in O(m \times \log n), where m and n are the lengths of nums1 and nums2 respectively.
What is the space complexity of LeetCode 1855. Maximum Distance Between a Pair of Values?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1855. Maximum Distance Between a Pair of Values cover?
LeetCode 1855. Maximum Distance Between a Pair of Values is tagged Array, Two Pointers and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview