FastPrepCount One-Swap Number Pairs
Problem · Array

Count One-Swap Number Pairs

Learn this problem
MediumTiktok logoTiktokINTERNOA
See Tiktok hiring insights

Problem statement

You are given an array of positive integers numbers. Count the index pairs (i, j) such that i < j and one number in the pair can be transformed into the other by swapping at most one pair of digit positions.

No swap is required when the two numbers are already equal. Each pair of indices is counted once, even when several different digit swaps produce the same value.

Use each number's ordinary decimal representation without leading zeroes. A swapped representation that begins with 0 is invalid, so valid transformed numbers have the same number of digits.

Return the number of qualifying index pairs.

Function

countOneSwapPairs(numbers: int[]) → int

Examples

Example 1

numbers = [1,23,156,1650,651,165,32]return = 3

The qualifying pairs are 23 with 32, 156 with 651, and 156 with 165. Therefore, the result is 3.

Example 2

numbers = [123,321,123]return = 3

The two copies of 123 form a qualifying pair without a swap. Each copy of 123 also pairs with 321 by swapping the first and last digits, for 3 pairs in total.

Constraints

  • 1 ≤ numbers.length ≤ 10^4
  • 1 ≤ numbers[i] ≤ 10^9

More Tiktok problems

drafts saved locally
public int countOneSwapPairs(int[] numbers) {
    // Write your code here.
}
numbers[1,23,156,1650,651,165,32]
expected3
checking account