Similar Problems

Similar Problems not available

Number Of Pairs Satisfying Inequality - Leetcode Solution

Companies:

LeetCode:  Number Of Pairs Satisfying Inequality Leetcode Solution

Difficulty: Hard

Topics: binary-search array  

Problem:

Given two arrays nums1 and nums2, return the number of pairs (i, j) such that i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j].

Example:

Input: nums1 = [2,1,2], nums2 = [1,2,1] Output: 1 Explanation: The pairs that satisfy the condition are:

  • (0, 2): nums1[0] + nums1[2] = 4 > nums2[0] + nums2[2] = 2 + 1 = 3.

Solution:

To solve this problem, we can use brute force approach where we check all possible pairs of (i, j) such that i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j]. But this approach has O(n^2) time complexity and may not work for large input sizes.

A better approach is to sort the arrays nums1 and nums2 in non-descending order. Then, for each i in nums1, we can find the maximum index j in nums2 such that nums1[i] + nums1[j] > nums2[i] + nums2[j]. To find such j, we can use binary search as both arrays are sorted. Once we have found the maximum index j for an i, all indices greater than j also satisfy the inequality. Therefore, we can add n - j - 1 to our answer. Finally, we can sum up the answer for all i in nums1.

The time complexity of this approach is O(n log n) as we use binary search to find j for each i.

Here is the Python code for the solution:

def binary_search(nums, target): # Returns the maximum index i such that nums[i] <= target left = 0 right = len(nums) - 1 index = -1 while left <= right: mid = (left + right) // 2 if nums[mid] <= target: index = mid left = mid + 1 else: right = mid - 1 return index

def num_pairs(nums1, nums2): nums1.sort() nums2.sort() n = len(nums1) m = len(nums2) ans = 0 for i in range(n): j = binary_search(nums2, nums1[i] + nums1[-1]) if j != -1: ans += m - j - 1 return ans

nums1 = [2,1,2] nums2 = [1,2,1] print(num_pairs(nums1, nums2)) # Output: 1

Number Of Pairs Satisfying Inequality Solution Code

1