1814. Count Nice Pairs in an Array

Introduction:

The problem involves identifying pairs of indices in an array that satisfy certain conditions, with a specific mathematical operation. This blog will discuss the problem, the provided solution, and break down the code for a better understanding.

Problem Overview:

The goal is to find the count of such nice pairs of indices. Due to the potential size of the result, it should be returned modulo (10^9 + 7).

Provided Solution:

The solution is implemented in Java and involves the following steps:

First we will simplify the given expression i in one side and j on other side. Then we end up with following expression.

nums[i] - rev(nums[i]) == nums[j] - rev(nums[j])
  1. Calculate the difference between each element and its reverse and store them in an array subtracted.
  2. Use a HashMap to store the frequency of each element in the subtracted array.
  3. Iterate through the HashMap, calculate the count of nice pairs, and accumulate the result.
  4. Return the final count modulo (10^9 + 7).

Code Breakdown:
Let’s break down the key parts of the provided Java code:

class Solution {
    public int countNicePairs(int[] nums) {
       
        int subtracted[] = new int[nums.length];
        for(int i=0;i<nums.length;i++) {
            subtracted[i] = nums[i] - reverse(nums[i]);
        }
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0;i<nums.length;i++) {
            if(map.containsKey(subtracted[i])) {
                map.put(subtracted[i], map.get(subtracted[i])+ 1);
            } else {
                map.put(subtracted[i], 1);
            }
        }
        long mod = 1000000007;
        long ans = 0;
        for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
            long freq = entry.getValue();
            int key = entry.getKey();
            if (freq > 1) {
                System.out.println(freq +" "+ key);
                ans = (ans + ((freq * (freq -1))/2)%mod)%mod;
            }
        }
        return (int)ans;
    }
    private int reverse(int i) {
        StringBuilder sb = new StringBuilder();
        sb.append(i);
        return Integer.parseInt(sb.reverse().toString());
    }
}

Conclusion:
This blog has discussed the problem of finding nice pairs in arrays, presented a Java solution, and explained the key components of the code. Understanding the provided solution is crucial for tackling similar mathematical and array manipulation problems.

Related Post