Leetcode #1885: Count Pairs in Two Arrays
In this guide, we solve Leetcode #1885 Count Pairs in Two Arrays 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
Given two integer arrays nums1 and nums2 of length n, count the pairs of indices (i, j) such that i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j]. Return the number of pairs satisfying the condition.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Two Pointers, Binary Search, Sorting
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 = [2,1,2,1], nums2 = [1,2,1,2]
Output: 1
Explanation: The pairs satisfying the condition are:
- (0, 2) where 2 + 2 > 1 + 1.
Python Solution
class Solution:
def countPairs(self, nums1: List[int], nums2: List[int]) -> int:
nums = [a - b for a, b in zip(nums1, nums2)]
nums.sort()
l, r = 0, len(nums) - 1
ans = 0
while l < r:
while l < r and nums[l] + nums[r] <= 0:
l += 1
ans += r - l
r -= 1
return ans
Complexity
The time complexity is , and the space complexity is . 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.