Ctrl K

One-Swap Twin Numbers

Medium
You are given an array of positive integers values. Call two numbers twins if they can be made equal with at most one operation: pick one of the two numbers and swap any two digits in it. Leading zeros are fine after a swap: for example, 50 can become 05, which is just 5. Return the number of index pairs i < j such that values[i] and values[j] are twins. Equal numbers are twins too; they need no swap at all.
Example 1
values=[13, 31, 130, 5] → 2

13 and 31: swap the digits of 13. 31 and 130: swap the 1 and the 0 in 130 to get 031, which is 31. No other pair works.

Example 2
values=[7, 7, 70] → 3

The two 7s are already equal, and 70 becomes 07 = 7 after one swap. All three pairs count.

Example 3
values=[123, 312] → 0

All three positions differ, which a single swap cannot fix.

Constraints
  • 2 ≤ len(values) ≤ 100
  • 1 ≤ values[i] ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwins Within Two Swaps HardMore Than a Third of the Votes MediumMost Common Values MediumJobs With a Cooldown MediumMost Searched Words Medium
loading Python…
Input
values=[13, 31, 130, 5]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.