Solving Leetcode Interviews in Seconds with AI: Count Nice Pairs in an Array
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1814" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: 0 <= i < j < nums.length nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7. Example 1: Input: nums = [42,11,1,97] Output: 2 Explanation: The two pairs are: - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. Example 2: Input: nums = [13,10,35,24,76] Output: 4 Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109
Explanation
Here's the breakdown of the approach, followed by the Python code:
Key Idea: The condition
nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])can be rearranged tonums[i] - rev(nums[i]) == nums[j] - rev(nums[j]). Therefore, we can calculate this difference for each number in the array and count the occurrences of each difference.Efficient Counting: Use a hash map (dictionary in Python) to store the counts of each difference, allowing for efficient lookups and updates. This avoids nested loops.
Modulo Arithmetic: Apply the modulo operator
% (10**9 + 7)during the count aggregation to prevent integer overflow and ensure the result remains within the required range.Complexity:
- Runtime: O(n), where n is the length of the input array
nums. - Storage: O(n) in the worst case, to store the differences in the hash map.
- Runtime: O(n), where n is the length of the input array
Code
def countNicePairs(nums):
"""
Counts the number of nice pairs in an array of non-negative integers.
Args:
nums: A list of non-negative integers.
Returns:
The number of nice pairs modulo 10^9 + 7.
"""
def rev(x):
"""Reverses a non-negative integer."""
reversed_x = 0
while x > 0:
reversed_x = reversed_x * 10 + x % 10
x //= 10
return reversed_x
diff_counts = {}
nice_pair_count = 0
modulo = 10**9 + 7
for num in nums:
diff = num - rev(num)
if diff in diff_counts:
nice_pair_count = (nice_pair_count + diff_counts[diff]) % modulo
diff_counts[diff] += 1
else:
diff_counts[diff] = 1
return nice_pair_count