LeetCode 3267: Count Almost Equal Pairs II

Problem Description

Explanation:

To solve this problem, we can iterate through each pair of numbers in the given array and check if they are almost equal. We can achieve this by sorting the digits of each number and comparing them. If the sorted digits are equal, or one is a permutation of the other, then the numbers are almost equal.

  • First, we define a helper function to sort the digits of a number.
  • Then, we iterate through all pairs of numbers in the array.
  • For each pair, we sort the digits of both numbers and check if they are equal or one is a permutation of the other.
  • If they meet the conditions, we increment the count of almost equal pairs.

The time complexity of this approach is O(n^2 * k * log(k)), where n is the number of elements in the array and k is the maximum number of digits in an element. The space complexity is O(1).

:

Solutions

class Solution {
    public int countAlmostEqualPairs(int[] nums) {
        int n = nums.length;
        int count = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (areAlmostEqual(nums[i], nums[j])) {
                    count++;
                }
            }
        }
        
        return count;
    }
    
    private boolean areAlmostEqual(int num1, int num2) {
        String s1 = sortDigits(num1);
        String s2 = sortDigits(num2);
        
        return s1.equals(s2) || s1.length() == s2.length() && s1.chars().allMatch(ch -> s2.contains(String.valueOf((char) ch)));
    }
    
    private String sortDigits(int num) {
        char[] digits = String.valueOf(num).toCharArray();
        Arrays.sort(digits);
        return new String(digits);
    }
}

Loading editor...