↓Skip to main content
  1. LeetCode/

LeetCode 1814: Count Nice Pairs in an Array

·1 min· ·
LeetCode Medium Array Hash-Table Math Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2024-04-17

  • Submissions: Wrong Answer → Accepted

Approach
#

Rearranging nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) gives nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]): each side depends on one index only. Map every number to x - rev(x); a value seen c times yields c(c - 1) / 2 pairs (Hash Table Template 1, the pair count of Math Template 1). Return the answer modulo 10^9 + 7.

My Attempts
#

Attempt 1 had the right approach but forgot the modulus, failing on large answers; adding % 1000000007 passed.

Solution
#

class Solution:
    def countNicePairs(self, nums: List[int]) -> int:
        cnt = Counter(x - int(str(x)[::-1]) for x in nums)
        return sum(c * (c - 1) // 2 for c in cnt.values()) % (10**9 + 7)

Complexity
#

Time O(n log M), space O(n).

Mistakes to Avoid
#

  • The problem requires the modulus.
  • Comparing all pairs is O(n²); rearrange so each side involves one index.

Interview Explanation
#

Rearranging the condition to nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]) gives each number its own key; a key seen c times contributes c choose 2 pairs, and I take the modulus. Time O(n log M).

Related

LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid
·2 mins
LeetCode Medium Array Hash-Table Matrix Counting
LeetCode 3071 note: count each value on and off the Y, enumerate the Y value a and background value b (a != b), and take the fewest cells to change
LeetCode 229: Majority Element II
·2 mins
LeetCode Medium Array Hash-Table Sorting Counting
LeetCode 229 note: at most two values can exceed n / 3; Boyer-Moore keeps two candidates and a second pass verifies their counts
LeetCode 914: X of a Kind in a Deck of Cards
·2 mins
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 note: every card count must be divisible by one X >= 2, i.e. the GCD of all counts is at least 2
LeetCode 313: Super Ugly Number
·2 mins
LeetCode Medium Array Math Dynamic-Programming
LeetCode 313 note: generalizing LC 264 with one pointer per prime; with a heap, avoid pushing the same number many times
LeetCode 396: Rotate Function
·2 mins
LeetCode Medium Array Math Dynamic-Programming
LeetCode 396 note: F(k) and F(k - 1) differ by one formula: F(k) = F(k - 1) + sum - n × the element moved to the front
LeetCode 264: Ugly Number II
·2 mins
LeetCode Medium Hash-Table Math Dynamic-Programming Heap-Priority-Queue
LeetCode 264 note: three pointers mark the next ugly numbers to multiply by 2, 3 and 5; take the minimum each time and advance every pointer that produced it