In an array nums, a pair of indices is called a "bad pair" if and . You need to find the total number of bad pairs in the array. This problem is about calculating the complement: it's often easier to count "good pairs" and subtract them from the total number of possible pairs.
Companies like Microsoft and Google use this problem to see if a candidate can recognize mathematical patterns and optimize a quadratic brute-force approach. The condition for a "good pair" is , which can be rearranged to . This simple algebraic shift allows the problem to be solved using a frequency map in linear time.
The pattern used is Mathematical Rearrangement and Complementary Counting with a Hash Table.
Array: [4, 1, 3, 3]
[4, 0, 1, 0].{4: 1, 0: 2, 1: 1}.The most common mistake is attempting to check all pairs using a nested loop, which is and will time out for large arrays. Another mistake is forgetting to use 64-bit integers (long) for the counts, as the number of pairs can grow very large ( for ).
Always look for the "total minus something" strategy when counting "bad" or "invalid" items. If the condition for being "bad" is complex, check if the condition for being "good" is simpler to calculate using a Hash Map.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Number of Distinct Integers After Reverse Operations | Medium | Solve | |
| Count Nice Pairs in an Array | Medium | Solve | |
| Sum of Digit Differences of All Pairs | Medium | Solve | |
| Number of Good Pairs | Easy | Solve | |
| Find The Least Frequent Digit | Easy | Solve |