Count Almost Equal Pairs II - Problem

You are given an array nums consisting of positive integers. We call two integers x and y almost equal if both integers can become equal after performing the following operation at most twice:

Choose either x or y and swap any two digits within the chosen number.

Return the number of indices i and j in nums where i < j such that nums[i] and nums[j] are almost equal.

Note that it is allowed for an integer to have leading zeros after performing an operation.

Input & Output

Example 1 — Basic Almost Equal
$ Input: nums = [3,12,30,17,21]
Output: 2
💡 Note: The almost equal pairs are (12,21) - swap 1↔2 in 12 to get 21, and (30,3) - 30→03→3 with leading zero allowed
Example 2 — No Valid Pairs
$ Input: nums = [1,1,1,1,1]
Output: 10
💡 Note: All numbers are identical, so all C(5,2) = 10 pairs are almost equal (0 swaps needed)
Example 3 — Complex Swapping
$ Input: nums = [123,321]
Output: 1
💡 Note: Can make 123→321 with 2 swaps: 123→321 (swap positions 0↔2), so this pair is almost equal

Constraints

  • 1 ≤ nums.length ≤ 3000
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Count Almost Equal Pairs II: nums = [3,12,30,17,21]312301721index 0index 1index 2index 3index 4Almost Equal Pairs Found:Pair (12,21): swap 1↔2 → 21Pair (3,30): 30→03→3 allowedOutput: 2 pairs
Understanding the Visualization
1
Input Array
Array of positive integers to analyze
2
Check Pairs
For each pair, determine if almost equal with ≤2 swaps
3
Count Result
Return total number of valid almost equal pairs
Key Takeaway
🎯 Key Insight: Two numbers are almost equal if they have identical digit frequencies and differ in at most 4 positions (resolvable with 2 swaps)
Asked in
Google 15 Meta 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
180 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen