Count Pairs in Two Arrays — LeetCode 1885 Python Solution
- Problem
- #1885
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums1 = [2,1,2,1], nums2 = [1,2,1,2]
- Output
- 1
- Explanation
- The pairs satisfying the condition are:
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 1885. Count Pairs in Two Arrays 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 1885. Count Pairs in Two Arrays?
- LeetCode 1885. Count Pairs in Two Arrays is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1885. Count Pairs in Two Arrays?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 1885. Count Pairs in Two Arrays?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1885. Count Pairs in Two Arrays cover?
- LeetCode 1885. Count Pairs in Two Arrays is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.
- Is LeetCode 1885. Count Pairs in Two Arrays a premium problem?
- Yes. LeetCode 1885. Count Pairs in Two Arrays is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.