Ctrl K

Twins Within Two Swaps

Hard
You are given an array of positive integers values. One operation picks one of two numbers and swaps any two of its digits. Leading zeros may appear after an operation and are simply dropped (for example, 310 can become 013 = 13). Call two numbers **twins** if they can be made equal with at most **two** such operations, both applied to the same number or one to each. Count the index pairs i < j for which values[i] and values[j] are twins.
Example 1
values=[1234, 2143, 2341] → 2

1234 and 2143 are twins: swap 1 with 2, then 3 with 4. 2143 and 2341 are twins too: one swap of 1 and 3 is enough. Turning 1234 into 2341, however, takes three swaps, not two. That makes 2 pairs.

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

Leading zeros are allowed: swapping the digits of 70 gives 07 = 7, and in 700 swapping the 7 with the last zero gives 007 = 7, or with the first zero, 070 = 70. All 3 pairs are twins.

Example 3
values=[45, 54, 45] → 3

The two 45s are twins with no swaps at all, and each of them is a twin of 54. That makes 3 pairs.

Constraints
  • 2 ≤ len(values) ≤ 10⁴
  • 1 ≤ values[i] < 10⁷
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsOne-Swap Twin Numbers MediumBalanced Cuts After One Replacement HardOriginal Array From Two Shifts HardThe Candidate With Most Votes EasyMore Than a Third of the Votes Medium
loading Python…
Input
values=[1234, 2143, 2341]
Expected
2

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