Leetcode 1814: Count Nice Pairs in an Array

grid47
grid47
Exploring patterns and algorithms
May 9, 2024 5 min read

You are given an array of non-negative integers. A pair of indices (i, j) is nice if nums[i] + rev(nums[j]) equals nums[j] + rev(nums[i]). Return the number of nice pairs modulo 10^9 + 7.
Problem
Approach
Steps
Complexity
Input: The input consists of an array nums with non-negative integers.
Example: nums = [12, 21, 34, 43]
Constraints:
• 1 <= nums.length <= 10^5
• 0 <= nums[i] <= 10^9
Output: Return the number of nice pairs of indices modulo 10^9 + 7.
Example: Output: 2
Constraints:
• The output should be an integer, modulo 10^9 + 7.
Goal: Count the number of nice pairs (i, j) in the array that satisfy the condition nums[i] + rev(nums[j]) = nums[j] + rev(nums[i]).
Steps:
• For each number in the array, calculate the difference between nums[i] and rev(nums[i]).
• Use a hash map to count how many times each difference occurs.
• For each difference count greater than 1, calculate how many pairs of indices can be formed.
• Return the total number of nice pairs modulo 10^9 + 7.
Goal: The input will always meet the constraints listed below.
Steps:
• The length of nums is between 1 and 10^5.
• Each element of nums is between 0 and 10^9.
Assumptions:
• All numbers are non-negative integers.
• The solution must be efficient due to the large input size.
Input: nums = [12, 21, 34, 43]
Explanation: In this case, the pairs (0,1) and (2,3) are nice because the sum of each pair and their reversed numbers are equal.

Input: nums = [5, 100, 100, 500]
Explanation: The only nice pair is (1,2), where nums[1] + rev(nums[2]) = nums[2] + rev(nums[1]).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus