Solution: Count Pairs in Two Arrays

Let’s solve the Count Pairs in Two Arrays problem using the Sort and Search pattern.

Statement

You are given two positive integer arrays, nums1 and nums2, both of length nn. Your task is to count and return the number of pairs of indexes (i,j)(i, j) where:

  • i<ji < j , and

  • nums1[i]+nums1[j]>nums2[i]+nums2[j]\text{nums1}[i] + \text{nums1}[j] > \text{nums2}[i] + \text{nums2}[j]

In simpler terms, the sum of two elements from nums1 must be greater than that of the corresponding elements from nums2.

Constraints:

  • n=n = nums1.length == nums2.length

  • 1n1031 \leq n \leq 10^3

  • 11 \leq nums1[i], nums2[i] 104\leq 10^4

Solution

A brute force approach would involve iterating through all pairs (i,j)(i, j) using nested loops. For each pair:

  1. Compute nums1[i]+nums1[j]\text{nums1}[i] + \text{nums1}[j].

  2. Compare it with nums2[i]+nums2[j]\text{nums2}[i] + \text{nums2}[j].

  3. Increment a counter if the condition is satisfied.

However, this approach requires O(n2)O(n^2) comparisons, which is inefficient for large inputs.

To optimize, we can simplify the condition:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.