Problem Description
Given two 0-indexed integer arrays nums1 and nums2 of equal length and an integer diff, count the number of index pairs (i, j) with 0 <= i < j < n such that: nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff. In other words, after rearranging terms, we need to count pairs with: (nums1[i] - nums2[i]) <= (nums1[j] - nums2[j]) + diff.
Key Insights
- Transform the problem by defining a new array value: diff_arr[i] = nums1[i] - nums2[i].
- The inequality becomes: diff_arr[i] <= diff_arr[j] + diff for i < j.
- For every index j, count how many earlier indices i have a diff_arr value <= diff_arr[j] + diff.
- Use data structures such as Binary Indexed Tree (Fenwick Tree) or balanced BST to count the number of valid indices efficiently.
- Discretize the values since nums1 and nums2 lie in a moderate range but the computed differences can be shifted by diff.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting for discretization and BIT operations for each element. Space Complexity: O(n) for the BIT and the discretized mapping.
Solution
The idea is to pre-compute an array diff_arr where each element is computed as nums1[i] - nums2[i]. The problem then reduces to counting, for each index j, the number of indices i < j that satisfy: diff_arr[i] <= diff_arr[j] + diff. A Binary Indexed Tree (BIT) is used to maintain counts of previously seen diff_arr values (after discretization). We discretize the possible values (both diff_arr and diff_arr[j] + diff) to map them onto indices in the BIT. As we iterate through diff_arr from left to right, we query the BIT for how many indices have values less than or equal to diff_arr[j] + diff. Then update the BIT with the current diff_arr[j]. This counts all valid pairs in an efficient manner.