LeetCode 3267: Count Almost Equal Pairs II Solution
Master LeetCode problem 3267 (Count Almost Equal Pairs II), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3267. Count Almost Equal Pairs II
Problem Explanation
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).
:
Solution Code
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);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3267 (Count Almost Equal Pairs II)?
This page provides optimized solutions for LeetCode problem 3267 (Count Almost Equal Pairs II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3267 (Count Almost Equal Pairs II)?
The time complexity for LeetCode 3267 (Count Almost Equal Pairs II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3267 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3267 in Java, C++, or Python.