Magicsheet logo

Count Almost Equal Pairs I

Medium
95%
Updated 6/1/2025

Count Almost Equal Pairs I

What is this problem about?

The Count Almost Equal Pairs I interview question involves an array of integers. Two integers are "almost equal" if you can make them equal by swapping at most two digits in one of them. You need to find the total number of pairs (i, j) in the array such that nums[i] and nums[j] are almost equal. Note that leading zeros are handled such that numbers like 3 and 30 could be comparable if the digit counts allow.

Why is this asked in interviews?

Meta asks the Count Almost Equal Pairs I coding problem to test your ability to handle string/digit manipulation and pair-wise comparisons efficiently. It evaluates whether you can define a robust "check" function for the swap condition and whether you can optimize the search using a Hash Table or Sorting.

Algorithmic pattern used

The problem uses Enumeration / Hash Table.

  1. Define a helper function isAlmostEqual(a, b):
    • Convert both numbers to strings and pad with leading zeros so they have the same length.
    • Count the number of positions where characters differ.
    • If differences > 2, return false.
    • If differences == 0, return true.
    • If differences == 2, check if swapping the two differing characters in one string makes it equal to the other.
  2. Iterate through all pairs (i, j) and count how many satisfy the condition.

Example explanation

nums = [3, 30]

  1. Convert to strings: "03" and "30".
  2. Differences: index 0 (0 != 3) and index 1 (3 != 0). Total differences = 2.
  3. Swap characters in "03": results in "30".
  4. "30" == "30". The pair is "almost equal".

Common mistakes candidates make

  • Leading Zeros: Failing to pad numbers with zeros, which makes comparing 3 and 30 (or 123 and 1230) difficult.
  • Swap Logic: Only checking the number of differences without verifying if a swap actually resolves the difference.
  • Complexity: Not realizing that for a small array, O(N^2) is fine, but for larger arrays, you might need to generate all possible "swapped" versions of each number and store them in a map.

Interview preparation tip

Whenever a problem mentions "swapping digits," think about converting the number to a character array. It’s much easier to swap elements in an array than to manipulate a string or perform math on the integer directly.

Similar Questions