#3267

Count Almost Equal Pairs II

Hard
ArrayHash TableSortingCountingEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

Instead of generating all possible swaps, we can use a frequency map to count how many times each digit appears in each number. This allows us to quickly determine if two numbers can be made equal with up to two swaps.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a frequency map for each number in the array, counting occurrences of each digit.
  2. 2Step 2: Store these frequency maps in a list.
  3. 3Step 3: Compare each pair of frequency maps to see if they can be made equal with up to two swaps.
solution.py22 lines
1from collections import Counter
2
3def countAlmostEqualPairs(nums):
4    def digit_count(num):
5        return Counter(str(num))
6
7    count = 0
8    n = len(nums)
9    freq_maps = [digit_count(num) for num in nums]
10    for i in range(n):
11        for j in range(i + 1, n):
12            if can_be_equal(freq_maps[i], freq_maps[j]):
13                count += 1
14    return count
15
16
17def can_be_equal(map1, map2):
18    diff = 0
19    for digit in set(map1.keys()).union(map2.keys()):
20        diff += abs(map1[digit] - map2[digit])
21    return diff <= 4  # Up to 2 swaps means 4 differences
22

Complexity note: The complexity remains O(n²) due to the pairwise comparison, but we reduce the overhead of generating swaps by using frequency maps, making it more efficient in practice.

  • 1Understanding how to manipulate digits can lead to different representations of numbers.
  • 2Using frequency maps allows for efficient comparisons without generating all possible swaps.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.