Count of pairs in Array with difference equal to the difference with digits reversed
Last Updated :
15 Nov, 2021
Given an array arr[] of N integers, the task is to find the number of pairs of array elements (arr[i], arr[j]) such that the difference between the pairs is equal to the difference when the digits of both the numbers are reversed.
Examples:
Input: arr[] = {42, 11, 1, 97}
Output: 2
Explanation:
The valid pairs of array elements are (42, 97), (11, 1) as:
1. 42 - 97 = 24 - 79 = (-55)
2. 11 - 1 = 11 - 1 = (10)
Input: arr[] = {1, 2, 3, 4}
Output: 6
Approach: The given problem can be solved by using Hashing which is based on the following observations:
A valid pair (i, j) will follow the equation as
=> arr[i] - arr[j] = rev(arr[i]) - rev(arr[j])
=> arr[i] - rev(arr[i]) = arr[j] - rev(arr[j])
Follow the below steps to solve the problem:
- Now, create a function reverseDigits, which will take an integer as an argument and reverse the digits of that integer.
- Store the frequency of values arr[i] - rev(arr[i]) in an unordered map, say mp.
- For each key(= difference) of frequency X the number of pairs that can be formed is given by \binom{X}{2} = \frac{X * (X - 1)}{2} .
- The total count of pairs is given by the sum of the value of the above expression for each frequency stored in the map mp.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to reverse the digits
// of an integer
int reverseDigits(int n)
{
// Convert the given number
// to a string
string s = to_string(n);
// Reverse the string
reverse(s.begin(), s.end());
// Return the value of the string
return stoi(s);
}
int countValidPairs(vector<int> arr)
{
// Stores resultant count of pairs
long long res = 0;
// Stores the frequencies of
// differences
unordered_map<int, int> mp;
for (int i = 0; i < arr.size(); i++) {
mp[arr[i] - reverseDigits(arr[i])]++;
}
// Traverse the map and count pairs
// formed for all frequency values
for (auto i : mp) {
long long int t = i.second;
res += t * (t - 1) / 2;
}
// Return the resultant count
return res;
}
// Driver Code
int main()
{
vector<int> arr = { 1, 2, 3, 4 };
cout << countValidPairs(arr);
return 0;
}
Java
// Java program for the above approach
import java.util.HashMap;
class GFG {
// Function to reverse the digits
// of an integer
public static int reverseDigits(int n)
{
// Convert the given number
// to a string
String s = String.valueOf(n);
// Reverse the string
s = new StringBuffer(s).reverse().toString();
// Return the value of the string
return Integer.parseInt(s);
}
public static int countValidPairs(int[] arr)
{
// Stores resultant count of pairs
int res = 0;
// Stores the frequencies of
// differences
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
if (mp.containsKey(arr[i] - reverseDigits(arr[i]))) {
mp.put(arr[i] - reverseDigits(arr[i]), mp.get(arr[i] - reverseDigits(arr[i])) + 1);
} else {
mp.put(arr[i] - reverseDigits(arr[i]), 1);
}
}
// Traverse the map and count pairs
// formed for all frequency values
for (int i : mp.keySet()) {
int t = mp.get(i);
res += t * (t - 1) / 2;
}
// Return the resultant count
return res;
}
// Driver Code
public static void main(String args[])
{
int[] arr = { 1, 2, 3, 4 };
System.out.println(countValidPairs(arr));
}
}
// This code is contributed by saurabh_jaiswal.
Python3
# python program for the above approach
# Function to reverse the digits
# of an integer
def reverseDigits(n):
# Convert the given number
# to a string
s = str(n)
# Reverse the string
s = "".join(reversed(s))
# Return the value of the string
return int(s)
def countValidPairs(arr):
# Stores resultant count of pairs
res = 0
# Stores the frequencies of
# differences
mp = {}
for i in range(0, len(arr)):
if not arr[i] - reverseDigits(arr[i]) in mp:
mp[arr[i] - reverseDigits(arr[i])] = 1
else:
mp[arr[i] - reverseDigits(arr[i])] += 1
# Traverse the map and count pairs
# formed for all frequency values
for i in mp:
t = mp[i]
res += (t * (t - 1)) // 2
# Return the resultant count
return res
# Driver Code
if __name__ == "__main__":
arr = [1, 2, 3, 4]
print(countValidPairs(arr))
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to reverse the digits
// of an integer
public static int reverseDigits(int n)
{
// Convert the given number
// to a string
string s = n.ToString();
// Reverse the string
char[] arr = s.ToCharArray();
Array.Reverse(arr);
string st = new string(arr);
// Return the value of the string
return Int32.Parse(st);
}
public static int countValidPairs(int[] arr)
{
// Stores resultant count of pairs
int res = 0;
// Stores the frequencies of
// differences
Dictionary<int, int> mp
= new Dictionary<int, int>();
for (int i = 0; i < arr.Length; i++) {
if (mp.ContainsKey(arr[i]
- reverseDigits(arr[i]))) {
mp[arr[i] - reverseDigits(arr[i])]
= mp[arr[i] - reverseDigits(arr[i])]
+ 1;
}
else {
mp[arr[i] - reverseDigits(arr[i])] = 1;
}
}
// Traverse the map and count pairs
// formed for all frequency values
foreach(int i in mp.Keys)
{
int t = mp[i];
res += t * (t - 1) / 2;
}
// Return the resultant count
return res;
}
// Driver Code
public static void Main()
{
int[] arr = { 1, 2, 3, 4 };
Console.WriteLine(countValidPairs(arr));
}
}
// This code is contributed by ukasp.
JavaScript
<script>
// Javascript program for the above approach
// Function to reverse the digits
// of an integer
function reverseDigits(n)
{
// Convert the given number
// to a string
let s = new String(n);
// Reverse the string
s = s.split("").reverse().join("");
// Return the value of the string
return parseInt(s);
}
function countValidPairs(arr)
{
// Stores resultant count of pairs
let res = 0;
// Stores the frequencies of
// differences
let mp = new Map();
for (let i = 0; i < arr.length; i++) {
let temp = arr[i] - reverseDigits(arr[i]);
if (mp.has(temp)) {
mp.set(temp, mp.get(temp) + 1);
} else {
mp.set(temp, 1);
}
}
// Traverse the map and count pairs
// formed for all frequency values
for (i of mp) {
let t = i[1];
res += (t * (t - 1)) / 2;
}
// Return the resultant count
return res;
}
// Driver Code
let arr = [1, 2, 3, 4];
document.write(countValidPairs(arr));
// This code is contributed by gfgking.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Count all distinct pairs with difference equal to K | Set 2 Given an integer array arr[] and a positive integer K, the task is to count all distinct pairs with differences equal to K. Examples: Input: arr[ ] = {1, 5, 3, 4, 2}, K = 3Output: 2Explanation: There are 2 distinct pairs with difference 3, the pairs are {1, 4} and {5, 2} Input: arr[] = {8, 12, 16, 4
6 min read
Count pairs from two arrays with difference exceeding K | set 2 Given two integer arrays arr[] and brr[] consisting of distinct elements of size N and M respectively and an integer K, the task is to find the count of pairs (arr[i], brr[j]) such that (brr[j] â arr[i]) > K. Examples: Input: arr[] = {5, 9, 1, 8}, brr[] = {10, 12, 7, 4, 2, 3}, K = 3Output: 6Expla
10 min read
Count three-digit numbers having difference X with its reverse Given an integer X, the task is to count the total number of three-digit numbers having difference X with its reverse. If no such number exists, then print -1. Examples: Input: X = 792Output : 10Explanation :901 - 109 = 792911 - 119 = 792921 - 129 = 792931 - 139 = 792941 - 149 = 792951 - 159 = 79296
6 min read
Count of subarrays whose product is equal to difference of two different numbers Given a non-negative array a, the task is to find the count of subarrays whose product of elements can be represented as the difference of two different numbers. Examples: Input: arr = {2, 5, 6} Output: 2 Explanation: Product of elements of subarray {5} can be represented as 32 - 22 is equal to 5 Pr
13 min read
Count pairs from two arrays with difference exceeding K Given two integer arrays arr[] and brr[] consisting of distinct elements of size N and M respectively and an integer K, the task is to find the count of pairs(arr[i], brr[j]) such that (brr[j] - arr[i]) > K. Examples: Input: arr[] = {5, 9, 1, 8}, brr[] {10, 12, 7, 4, 2, 3}, K = 3 Output: 6 Explan
9 min read
Count of integers having difference with its reverse equal to D Given an integer D, the task is to find the count of all possible positive integers N such that reverse(N) = N + D. Examples: Input: D = 63 Output: 2 Explanation: For N = 18, 18 + 63 = 81, which satisfies the condition N + D = reverse(N). For N = 29, 29 + 63 = 92, which satisfies the condition N + D
13 min read