Count Pairs in Two Arrays — LeetCode 1885 Python Solution

MediumLeetCode PremiumArrayTwo PointersBinary SearchSorting
Problem
#1885
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(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.

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