Maximum Distance Between a Pair of Values — LeetCode 1855 Python Solution
- Problem
- #1855
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times \log n), where m and n are the lengths of nums1 and nums2 respectively |
| Space | O(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.