Introduction
LeetCode 1855 β Maximum Distance Between a Pair of Values is a classic problem that beautifully demonstrates the power of the Two Pointer technique on sorted (non-increasing) arrays.
At first glance, it may feel like a brute-force problemβbut using the right observation, it can be solved efficiently in O(n) time.
In this article, we will cover:
- Problem intuition
- Why brute force fails
- Optimized two-pointer approach (your solution)
- Alternative approaches
- Time complexity analysis
π Problem Link
LeetCode: Maximum Distance Between a Pair of Values
Problem Statement
You are given two non-increasing arrays:
nums1nums2
A pair (i, j) is valid if:
i <= jnums1[i] <= nums2[j]
π Distance = j - i
Return the maximum distance among all valid pairs.
Examples
Example 1
Input:
nums1 = [55,30,5,4,2]
nums2 = [100,20,10,10,5]
Output:
2
Key Insight
The most important observation:
π This allows us to use two pointers efficiently instead of brute force.
β Naive Approach (Brute Force)
Idea
- Try all
(i, j)pairs - Check conditions
- Track maximum
Complexity
- Time: O(n Γ m) β
π This will cause TLE for large inputs (up to 10β΅)
β Optimized Approach: Two Pointers
Intuition
Use two pointers:
We try to:
- Expand
jas far as possible - Move
ionly when necessary
Key Logic
Java Code
Step-by-Step Dry Run
Input:
Execution:
- (0,0) β valid β distance = 0
- Move j β (0,1) β invalid β move i
- Continue...
Final best pair:
Why This Works
- Arrays are sorted (non-increasing)
- Moving
jincreases distance - Moving
ihelps find valid pairs
π No need to re-check previous elements
Complexity Analysis
Time Complexity
- O(n + m)
Each pointer moves at most once through the array.
Space Complexity
- O(1) (no extra space used)
Alternative Approach: Binary Search
Idea
For each i in nums1:
- Use binary search in
nums2 - Find farthest
jsuch that:
Complexity
- O(n log m)
Code (Binary Search Approach)
Two Pointer vs Binary Search
| Approach | Time | Space |
| Two Pointer | O(n + m) β | O(1) |
| Binary Search | O(n log m) | O(1) |
π Two pointer is optimal here
Key Takeaways
- Use two pointers when arrays are sorted
- Always look for monotonic properties
- Avoid brute force when constraints are large
- Greedy pointer movement can optimize drastically
Common Interview Patterns
This problem is related to:
- Two pointer problems
- Sliding window
- Binary search on arrays
- Greedy expansion
Conclusion
The Maximum Distance Between a Pair of Values problem is a great example of how recognizing array properties can drastically simplify the solution.
By using the two-pointer technique, we reduce complexity from O(nΒ²) to O(n)βa massive improvement.
Frequently Asked Questions (FAQs)
1. Why do we use two pointers?
Because arrays are sorted, allowing linear traversal.
2. Why not brute force?
It is too slow for large inputs (10β΅).
3. What is the best approach?
π Two-pointer approach




