Count Pairs in Two Arrays

Updated on 09 May, 2025
Count Pairs in Two Arrays header image

Problem Statement

Given two integer arrays, nums1 and nums2, each of the same length n, the task is to identify and count all pairs of indices (i, j) such that the condition i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j] are both satisfied. The return value should be the total number of such pairs.

Examples

Example 1

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.

Example 2

Input:

nums1 = [1,10,6,2], nums2 = [1,4,1,5]

Output:

5

Explanation:

The pairs satisfying the condition are:
- (0, 1) where 1 + 10 > 1 + 4.
- (0, 2) where 1 + 6 > 1 + 1.
- (1, 2) where 10 + 6 > 4 + 1.
- (1, 3) where 10 + 2 > 4 + 5.
- (2, 3) where 6 + 2 > 1 + 5.

Constraints

  • n == nums1.length == nums2.length
  • 1 <= n <= 105
  • 1 <= nums1[i], nums2[i] <= 105

Approach and Intuition

To solve this problem, we can use a straightforward approach to iterate over all potential pairs and count those which meet the given criteria. Let's breakdown the solution approach:

  1. Use a nested loop structure where the outer loop starts from index i = 0 to n-1 and the inner loop starts from index j = i + 1 to n. This ensures that we are only considering pairs (i, j) with i < j.
  2. For each pair (i, j), calculate the sums nums1[i] + nums1[j] and nums2[i] + nums2[j].
  3. Compare these sums, and if nums1[i] + nums1[j] is greater than nums2[i] + nums2[j], increment a counter.
  4. After all pairs are evaluated, the counter will represent the number of valid pairs, and this is the value that should be returned.

This method is direct but might not be efficient for very large arrays due to its O(n^2) time complexity, where n can go up to 105. Each pair of elements is checked individually, which becomes computationally expensive as n grows. However, for moderate sizes of n, this approach will work within reasonable time limits.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    long long totalValidPairs(vector<int>& numbers1, vector<int>& numbers2) {
        int len = numbers1.size();  // numbers2 has the identical length

        // Compute Delta[i] as numbers1[i] - numbers2[i]
        vector<int> Delta(len);
        for (int i = 0; i < len; i++) {
            Delta[i] = numbers1[i] - numbers2[i];
        }
        sort(begin(Delta), end(Delta));  // Sort differences

        // Calculate the total number of pairs
        long long pairCount = 0;
        int start = 0;
        int end = len - 1;
        while (start < end) {
            if (Delta[start] + Delta[end] > 0) {
                pairCount += end - start;
                end--;
            } else {
                start++;
            }
        }
        return pairCount;
    }
};

This summary guides you through implementing a C++ solution to compute the count of valid pairs in two arrays where the sum of the differences is positive.

  • Start by creating a function totalValidPairs which accepts two integer vectors numbers1 and numbers2 as parameters.
  • Determine the length of the vectors (assuming both have the same length).
  • For each index i in the range of the vectors' length, compute the difference between corresponding elements of numbers1 and numbers2; store these values in a vector Delta.
  • Sort the Delta vector in non-decreasing order.
  • Initialize two pointers, start set to the beginning of the Delta array and end set to the last element.
  • Iterate using a while loop as long as start is less than end. In the loop, check if the sum of the elements at the start and end pointers is greater than zero:
    • If true, increment the pairCount by the difference between end and start, then decrement the end pointer to examine the next pair.
    • If false, increment the start pointer to check the next potential valid pair.
  • Continue iterating until all potential pairs are examined.
  • Finally, return the pairCount which represents the total number of valid pairs where the sum of differences is positive.

This solution leverages sorting and two-pointer technique to efficiently find the pairs, reducing the potential complexity compared to a brute-force approach. Ensure to handle edge cases, such as empty input arrays, in your implementation.

java
class Solution {
    public long calculatePairs(int[] array1, int[] array2) {
        int length = array1.length; // array2 will be of the same length as array1

        // Array diffs will hold the result of array1[i] - array2[i]
        long[] diffs = new long[length];
        for (int i = 0; i < length; i++) {
            diffs[i] = array1[i] - array2[i];
        }
        Arrays.sort(diffs);

        // Counting pairs where the sum of differences is positive
        long pairs = 0;
        int start = 0;
        int end = length - 1;
        while (start < end) {
            if (diffs[start] + diffs[end] > 0) {
                pairs += end - start;
                end--;
            } else {
                start++;
            }
        }
        return pairs;
    }
}

The provided Java program defines a class Solution that includes a method for counting pairs in two arrays based on specific conditions. This method, calculatePairs, accepts two integer arrays of equal length and computes the number of index pairs (i, j) such that the sum of the differences array1[i] - array2[i] and array1[j] - array2[j] is positive.

Follow these high-level steps to understand the functionality:

  1. Calculate the difference between corresponding elements of array1 and array2, store these differences in a new array called diffs.
  2. Sort the diffs array.
  3. Initialize two pointers, start pointing to the beginning of the array and end pointing to the last element.
  4. Iterate through the diffs array using a while loop with the condition start < end:
    • Check if the sum of the elements at start and end is greater than zero. If true, compute the number of pairs that can be formed, add to pairs count, and decrement end.
    • If the condition is not met, increment start.
  5. Return the total count of such pairs.

This algorithm efficiently pairs elements from two arrays to maximize the number of valid pairs where the specified condition on the sum of differences holds true. By sorting and using a two-pointer technique, the implementation ensures that the solution is optimal and runs in O(n log n) time due to the sorting step.

python
class Solution:
    def sumPairs(self, array1, array2):
        count = len(array1)  # Ensure array2 is the same length

        # Compute differences between corresponding elements
        delta = [array1[i] - array2[i] for i in range(count)]
        delta.sort()

        # Find valid pairs
        total_pairs = 0
        begin = 0
        end = count - 1
        while begin < end:
            if delta[begin] + delta[end] > 0:
                total_pairs += end - begin
                end -= 1
            else:
                begin += 1
        return total_pairs

In the provided Python solution, the objective is to count the number of valid pairs (i, j) from two arrays such that the sum of the difference of the ith element of array1 and 'array2' with the jth element of array1 and array2 is greater than 0. Here's a concise explanation of how the solution achieves this:

  • First, the difference between corresponding elements of array1 and array2 is calculated and stored in a list called delta.
  • The delta list is then sorted to facilitate the pairing process.
  • Using a two-pointer technique (one starting at the beginning (begin) and one at the end (end)), the code evaluates the sum of pairs from both ends of the sorted list.
  • If the sum of the elements at the begin and end pointers is greater than 0, the number of pairs involving the element at the end index and all elements from the begin index up to end-1 is added to total_pairs. The end pointer is then decremented.
  • If the sum is not greater than 0, the begin pointer is incremented to explore the possibility of a valid pair with a higher value at the start of the array.
  • This process continues until the begin index is less than the end index.

The final total of valid pairs where the condition is met is returned by the function. This approach efficiently pairs elements to maximize the number of valid scenarios while avoiding the necessity to compare each element with every other element, thus lowering the algorithm complexity.

Comments

No comments yet.