#3265

Count Almost Equal Pairs I

Medium
ArrayHash TableSortingCountingEnumeration
LeetCode ↗

Approaches

💡

Intuition

Time Space

We will check every possible pair of numbers in the array to see if they can be made equal by swapping two digits in one of the numbers. This is straightforward but can be slow for larger arrays.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter to 0 for counting almost equal pairs.
  2. 2Step 2: Iterate through each pair of numbers (i, j) where i < j.
  3. 3Step 3: For each pair, check if swapping any two digits in either number can make them equal.
  4. 4Step 4: If they can be made equal, increment the counter.
  5. 5Step 5: Return the counter after checking all pairs.
solution.py23 lines
1# Full working Python code
2
3def can_be_equal(x, y):
4    x_str, y_str = str(x), str(y)
5    for i in range(len(x_str)):
6        for j in range(i + 1, len(x_str)):
7            swapped_x = list(x_str)
8            swapped_x[i], swapped_x[j] = swapped_x[j], swapped_x[i]
9            if ''.join(swapped_x) == y_str:
10                return True
11    return False
12
13def count_almost_equal_pairs(nums):
14    count = 0
15    n = len(nums)
16    for i in range(n):
17        for j in range(i + 1, n):
18            if can_be_equal(nums[i], nums[j]) or can_be_equal(nums[j], nums[i]):
19                count += 1
20    return count
21
22# Example usage:
23print(count_almost_equal_pairs([3, 12, 30, 17, 21]))  # Output: 2

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