
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to count nice pairs in an array in Python
Suppose we have an array called nums with non-negative values. We have to find number nice pairs of indices present in the array, if the answer is too large, then return answer mod 10^9+7. Here a pair of indices (i, j) is said to be nice when they satisfy all of these conditions: 1. 0 <= i < j < size of nums 2. nums[i] + rev(nums[j]) is same as nums[j] + rev(nums[i])
Note − Here rev() reverses only the positive part of an integer, so if rev(564) is there, it means 465, but if rev(540) is there, it returns 45.
So, if the input is like nums = [97,2,42,11], then the output will be 2 because there are two pairs (0,2) and (1,3), for the first one [97 + rev(42) = 97+24 = 121, and 42 + rev(97) = 42 + 79 = 121] and for the second one [2 + rev(11) = 2 + 11 = 13 and 11 + rev(2) = 13].
To solve this, we will follow these steps −
m :=(10^9) +7
dic := an empty map, whose default value is 0
for each num in nums, do
rev := reverse of num
increase dic[num - rev] by 1
res:= 0
for each val in list of all values of dic, do
res := res + quotient of (val*(val-1))/2
return res mod m
Example
Let us see the following implementation to get better understanding −
from collections import defaultdict def solve(nums): m = (10**9)+7 dic = defaultdict(int) for num in nums: rev=int(str(num)[::-1]) dic[num-rev]+=1 res=0 for val in dic.values(): res += (val*(val-1)) // 2 return res % m nums = [97,2,42,11] print(solve(nums))
Input
[97,2,42,11]
Output
2
- Related Articles
- Program to count number of nice subarrays in Python
- Python Program to Count Inversions in an array
- Program to count index pairs for which array elements are same in Python
- Count divisible pairs in an array in C++
- Python program to count Bidirectional Tuple Pairs
- Program to maximize number of nice divisors in Python
- Program to count pairs with XOR in a range in Python
- Python program to count pairs for consecutive elements
- Count Number of Nice Subarrays in C++
- Program to find longest nice substring using Python
- Python program to count the pairs of reverse strings
- Program to restore the array from adjacent pairs in Python
- Count of index pairs with equal elements in an array in C++
- C++ Program to Count Inversion in an Array
- Count all pairs of an array which differ in K bits in C++
