LeetCode 3265: Count Almost Equal Pairs I Solution
Master LeetCode problem 3265 (Count Almost Equal Pairs I), a medium 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.
3265. Count Almost Equal Pairs I
Problem Explanation
Explanation
To solve this problem, we can iterate through all pairs of numbers in the array and check if they are almost equal. Two numbers are almost equal if one can be transformed into the other by swapping two digits. We can achieve this by comparing the sorted versions of the numbers after converting them to strings. If the sorted strings are the same or can become the same by swapping two characters, then the pair is almost equal. We need to handle the case of leading zeros when comparing the strings.
- Time Complexity: O(n^2 * m * log m) where n is the number of elements in the array and m is the maximum number of digits in any element.
- Space Complexity: O(1)
Solution Code
class Solution {
public int countAlmostEqualPairs(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (isAlmostEqual(nums[i], nums[j])) {
count++;
}
}
}
return count;
}
private boolean isAlmostEqual(int num1, int num2) {
String num1Str = String.valueOf(num1);
String num2Str = String.valueOf(num2);
return sortString(num1Str).equals(sortString(num2Str));
}
private String sortString(String str) {
char[] arr = str.toCharArray();
Arrays.sort(arr);
return new String(arr);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3265 (Count Almost Equal Pairs I)?
This page provides optimized solutions for LeetCode problem 3265 (Count Almost Equal Pairs I) 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 3265 (Count Almost Equal Pairs I)?
The time complexity for LeetCode 3265 (Count Almost Equal Pairs I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3265 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3265 in Java, C++, or Python.