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 INPUT Array: nums 3 i=0 12 i=1 30 i=2 17 i=3 21 i=4 Almost Equal Examples: 3 --swap--> 03 --swap--> 30 (3, 30) are almost equal 12 --swap--> 21 (12, 21) are almost equal At most 2 swaps allowed per number comparison ALGORITHM STEPS 1 Generate Patterns For each num, create all possible 0,1,2 swap variants 2 Store in Frequency Map Map: pattern --> count of numbers producing it 3 Compare Pairs For i < j, check if patterns of nums[i] and nums[j] match 4 Count Matches Increment count for each valid almost equal pair Pattern Generation Example 3 --> {03, 30, 3} 12 --> {12, 21} 30 --> {30, 03, 3} 21 --> {21, 12} FINAL RESULT Almost Equal Pairs Found: Pair 1: (i=0, j=2) 3 and 30 OK - match via 2 swaps Pair 2: (i=1, j=4) 12 and 21 OK - match via 1 swap Output: 2 Total almost equal pairs where i < j Key Insight: Frequency Pattern Matching: Instead of checking all O(n^2) pairs naively, precompute all possible values each number can transform into via 0, 1, or 2 digit swaps. Store these in a hash map. Two numbers are almost equal if their transformation sets share a common value (pattern overlap). TutorialsPoint - Count Almost Equal Pairs II | Frequency Pattern Matching
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