Similar Problems
Similar Problems not available
Count The Number Of Fair Pairs - Leetcode Solution
Companies:
LeetCode: Count The Number Of Fair Pairs Leetcode Solution
Difficulty: Medium
Topics: sorting two-pointers array binary-search
Problem Statement:
Given two arrays of integers nums1 and nums2, return the number of pairs where i < j and nums1[i] - nums1[j] == nums2[i] - nums2[j].
A pair (i,j) is called fair if the above condition is true.
Solution:
We can use a hash map to store the frequency of all possible differences nums1[i] - nums1[j] - (nums2[i] - nums2[j]) for every i and j.
Then, we simply iterate through all possible pairs (i, j) and check if the difference calculated using the hash map is equal to nums1[i] - nums1[j] - (nums2[i] - nums2[j]). If it is, then we increment our answer.
Algorithm:
-
Initialize a counter fairPairs to 0.
-
Initialize a hash map diffFreq to store the frequency of all possible differences nums1[i] - nums1[j] - (nums2[i] - nums2[j]) for every i and j.
-
Iterate through each pair (i, j) from 0 to n-1 and calculate the difference using the formula nums1[i] - nums1[j] - (nums2[i] - nums2[j]). Store this difference in the diffFreq hash map.
-
Iterate through each pair (i, j) from 0 to n-1 and calculate the difference using the formula nums1[i] - nums1[j] - (nums2[i] - nums2[j]). Check if the difference exists in diffFreq and increment fairPairs by the frequency of this difference.
-
Return fairPairs as the answer.
Time Complexity:
The time complexity of this algorithm is O(n^2) because we are iterating through every possible pair (i, j) twice.
Space Complexity:
The space complexity of this algorithm is O(n^2) because we are storing the frequency of all possible differences nums1[i] - nums1[j] - (nums2[i] - nums2[j]) for every i and j in the hash map.
Code:
public int countNicePairs(int[] nums) { int n = nums.length; int mod = (int) 1e9 + 7; int[] rev = new int[n]; for (int i = 0; i < n; ++i) { rev[i] = reverseNum(nums[i]); } Map<Integer, Integer> mp = new HashMap<>(); int ans = 0; for (int i = 0; i < n; ++i) { ans = (ans + mp.getOrDefault(nums[i] - rev[i], 0)) % mod; mp.put(nums[i] - rev[i], mp.getOrDefault(nums[i] - rev[i], 0) + 1); } return ans; }
private int reverseNum(int num) { int res = 0; while (num > 0) { res = res * 10 + num % 10; num /= 10; } return res; }
Count The Number Of Fair Pairs Solution Code
1