Count Almost Equal Pairs I - Problem

You are given an array nums consisting of positive integers.

We call two integers x and y in this problem almost equal if both integers can become equal after performing the following operation at most once:

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: It is allowed for an integer to have leading zeros after performing an operation.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,12,30,17,21]
Output: 2
💡 Note: Almost equal pairs: (12,21) because 12→21 by swapping digits, and (30,3) because 30→03→3 by swapping. Total count is 2.
Example 2 — No Swaps Needed
$ Input: nums = [1,1,1,1,1]
Output: 10
💡 Note: All numbers are already equal, so every pair (i,j) where i
Example 3 — No Almost Equal Pairs
$ Input: nums = [123,456]
Output: 0
💡 Note: No way to make 123 and 456 equal by swapping digits in either number.

Constraints

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

Visualization

Tap to expand
Count Almost Equal Pairs I INPUT Array nums[] 3 i=0 12 i=1 30 i=2 17 i=3 21 i=4 Pairs to check (i < j): (3,12) (3,30) (3,17) (3,21) (12,30) (12,17) (12,21) (30,17) (30,21) (17,21) Almost Equal: Two numbers that become equal after swapping at most 2 digits in one number ALGORITHM STEPS 1 Generate Variants For each number, create all possible digit-swap versions 2 Store in HashMap Map original nums[j] to set of all its variants 3 Compare Pairs Check if nums[i] variant matches any nums[j] variant 4 Count Matches Increment counter for each almost equal pair Example: 3 and 30 3 --> "03" --> swap --> "30" 30 == 30 [OK - Match!] Similarly: 12 --> 21 [OK] FINAL RESULT Almost Equal Pairs Found: Pair 1: (3, 30) 3 --> "03" --> "30" indices (0, 2) Pair 2: (12, 21) 12 --> swap --> 21 indices (1, 4) OUTPUT 2 Total almost equal pairs in the array Key Insight: Instead of comparing all pairs directly, generate all possible single-swap variants for each number. Two numbers are "almost equal" if their variant sets overlap. Leading zeros allowed (3 becomes "03"). Time: O(n^2 * d^2) where d = max digits | Space: O(n * d^2) for storing variants TutorialsPoint - Count Almost Equal Pairs I | Optimized Digit Difference Check
Asked in
Google 25 Microsoft 20 Amazon 15
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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