StringBuilder IV

Not necessarily needed StringBuilder here, but the manipulation becomes much easier in strings than numbers, and since we need to swap elements to check for the IsAlmostEqual, it fits well here. Code is down below, cheers from Paddington, England! ACC

Count Almost Equal Pairs I - LeetCode

3265. Count Almost Equal Pairs I
Medium

You are given an array nums consisting of positive integers.

We call two integers x and y in this problem almost equal if both integers can become equal after performing the following operation at most once:

  • Choose either x or y and swap any two digits within the chosen number.

Return the number of indices i and j in nums where i < j such that nums[i] and nums[j] are almost equal.

Note that it is allowed for an integer to have leading zeros after performing an operation.

 

Example 1:

Input: nums = [3,12,30,17,21]

Output: 2

Explanation:

The almost equal pairs of elements are:

  • 3 and 30. By swapping 3 and 0 in 30, you get 3.
  • 12 and 21. By swapping 1 and 2 in 12, you get 21.

Example 2:

Input: nums = [1,1,1,1,1]

Output: 10

Explanation:

Every two elements in the array are almost equal.

Example 3:

Input: nums = [123,231]

Output: 0

Explanation:

We cannot swap any two digits of 123 or 231 to reach the other.

 

Constraints:

  • 2 <= nums.length <= 100
  • 1 <= nums[i] <= 106

public int CountPairs(int[] nums)
{
    int retVal = 0;

    for (int i = 0; i < nums.Length; i++)
    {
        for (int j = i + 1; j < nums.Length; j++)
        {
            if (IsAlmostEqual(nums[i], nums[j])) retVal++;
        }
    }

    return retVal;
}

private bool IsAlmostEqual(int a, int b)
{
    if (a == b) return true;

    StringBuilder sba = TransformToString(a);
    StringBuilder sbb = TransformToString(b);

    int[] indexesDiff = { -1, -1 };
    int index = 0;

    for (int i = 0; i < sba.Length; i++)
    {
        if (sba[i] != sbb[i])
        {
            if (index >= indexesDiff.Length) return false;
            indexesDiff[index] = i;
            index++;
        }
    }

    if (index != 2) return false;

    char temp = sba[indexesDiff[0]];
    sba[indexesDiff[0]] = sba[indexesDiff[1]];
    sba[indexesDiff[1]] = temp;

    return sba.ToString().Equals(sbb.ToString());
}

private StringBuilder TransformToString(int n)
{
    string str = n.ToString();

    while (str.Length < 6)
        str = "0" + str;

    return new StringBuilder(str);
}



Comments

Popular posts from this blog

Golang vs. C#: performance characteristics (simple case study)

ProjectEuler Problem 719 (some hints, but no spoilers)

Changing the root of a binary tree