Taro Logo

Count Pairs in Two Arrays

Medium
Asked by:
Shopee
Teradata
0 views
Topics:
ArraysTwo PointersBinary Search

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 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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of `nums1` and `nums2`, and what range of values can the elements inside these arrays take?
  2. Can the arrays contain negative numbers and zeros, or are we guaranteed that all elements are strictly positive integers?
  3. Are `nums1` and `nums2` guaranteed to be of the exact same length, and could they be empty or contain only a single element?
  4. Does the order of indices in the valid pair matter, or are we strictly looking for pairs where $i < j$?
  5. Can there be duplicate values across the arrays, and should identical values at different indices be treated as distinct pairs?

Brute Force Solution

Approach

Imagine you have two collections of items and you want to find every possible pairing between them. The brute force approach involves looking at every single item from the first collection and comparing it against every single item from the second collection.

Here's how the algorithm would work step-by-step:

  1. Pick the very first item from the first collection.
  2. Pair this item with the first item from the second collection and check if the pairing meets your goal.
  3. Next, pair the exact same item from the first collection with the second item from the second collection and check it again.
  4. Continue this process, pairing your current item with every remaining item in the second collection one by one.
  5. Once you have tested all possible pairings for your first item, move on to the second item in the first collection.
  6. Repeat the entire process of pairing this new item with every single item in the second collection.
  7. Keep doing this until every item in the first collection has been paired with every item in the second collection.
  8. Count up all the pairings that successfully met your goal along the way.

Code Implementation

def count_valid_pairs(first_collection, second_collection):
    successful_pair_count = 0

    # Iterate through every single item in the first collection to evaluate all possible pairings
    for current_first_item in first_collection:
        for current_second_item in second_collection:
            
            # Validate the specific pairing condition to determine if it meets our target goal
            if current_first_item + current_second_item > 0:
                successful_pair_count += 1

    # Return the accumulated total of all pairings that successfully met our criteria
    return successful_pair_count

Big(O) Analysis

Time Complexity
O(n²) – The brute force approach uses nested iterations where every single item in the first collection of size n is paired and checked against every item in the second collection of size n. For each of the n items in the outer loop, the inner loop runs n times to test all possible combinations. This leads to approximately n * n operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute force pairing process described requires only a few constant-space variables, such as loop counters to track the current positions in both collections and a running tally to count the successful pairings. No temporary lists, hash maps, or recursive stack frames are utilized to store intermediate results or visited items. Therefore, the auxiliary space remains entirely constant regardless of the input size, where N represents the number of elements in the collections.

Optimal Solution

Approach

Instead of checking every possible combination between the two collections, we can transform the problem by calculating the difference for each pair and rearranging them. This clever shift allows us to pair up items efficiently by sorting our options and quickly finding matches without unnecessary guessing.

Here's how the algorithm would work step-by-step:

  1. Look at every matching pair of items from the first and second groups, and calculate the difference between their values.
  2. Take all of those calculated differences and sort them in order from smallest to largest so they are easy to search through.
  3. Go through the sorted differences one by one and figure out how much you need to add to each item to meet the winning condition of the problem.
  4. Instead of searching from the beginning every time, use a shortcut to find where the qualifying items start in the sorted line.
  5. Count how many valid options exist beyond that point, knowing that everything further down the line will also satisfy the condition.
  6. Add up all those successful counts as you move along to get the final total of valid pairs.

Code Implementation

import bisect


def count_valid_pairs(first_array, second_array):
    
    # Transforming the inequality into a difference array allows us to isolate elements and sort them for efficient searching.
    difference_array = [first_element - second_element for first_element, second_element in zip(first_array, second_array)]
    
    difference_array.sort()
    total_valid_pairs = 0
    
    for current_index in range(len(difference_array)):
        current_difference = difference_array[current_index]
        
        # We need the inverse of the current difference to satisfy the inequality condition across the sorted boundary.
        target_threshold = -current_difference
        
        qualification_index = bisect.bisect_right(difference_array, target_threshold, current_index + 1)
        
        # Everything beyond the qualification index automatically satisfies the condition due to prior sorting.
        total_valid_pairs += len(difference_array) - qualification_index
        
    return total_valid_pairs

Big(O) Analysis

Time Complexity
O(n log n) – Calculating the difference for each of the n matching pairs in the two collections takes linear time, or O(n). Sorting these n calculated differences requires O(n log n) time. We then iterate through the sorted differences using a binary search approach, which takes O(log n) for each of the n elements, totaling O(n log n). Combining these sequential steps, the operations scale as n log n plus n, which simplifies to the dominant factor of O(n log n).
Space Complexity
O(n) – The auxiliary space is driven by the data structure used to store and sort the calculated differences between the matching pairs from the two input groups. Since we compute a difference for each corresponding pair, we generate a temporary list of size N, where N represents the number of elements in each of the two input arrays. The sorting operation and the subsequent two-pointer or binary search traversal operate on this array of size N without adding any additional scaling memory structures. Therefore, the extra memory required scales linearly with the input size N, leading to an overall auxiliary space complexity of O(N).

Edge Cases

Arrays of length less than 2
How to Handle:
Return zero immediately since no valid pair with i < j can be formed.
Arrays with negative numbers and zeros
How to Handle:
Algebraic rearrangement of the inequality correctly preserves correctness across negative domains without needing offset adjustments.
Maximum possible array lengths up to constraints
How to Handle:
Using an O(N log N) sorting or merging approach ensures the solution scales efficiently well within typical time limits.
All elements yielding identical transformed values
How to Handle:
Combinatorics or two-pointer counting correctly handles duplicate differences in logarithmic time during the sorted scan.
Extremely large extreme integer values near boundaries
How to Handle:
Rearranging the inequality to nums1[i] - nums2[i] > nums2[j] - nums1[j] prevents arithmetic overflow when calculating sums.
No valid pairs meeting the strict inequality condition
How to Handle:
The counter remains at zero and the algorithm naturally returns zero without failing.
All possible pairs forming valid solutions
How to Handle:
Using standard arithmetic accumulation prevents integer overflow when the total count reaches N*(N-1)/2.