question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
sort-array-by-increasing-frequency
Simple Solution in Java
simple-solution-in-java-by-s34-v9in
Use map to store element & count/frequency\n- Use priority queue to store key-value pair is custom sorted format (as required in question)\n- Store the elements
s34
NORMAL
2021-09-07T16:14:53.894311+00:00
2021-09-07T16:14:53.894355+00:00
388
false
- Use map to store element & count/frequency\n- Use priority queue to store key-value pair is custom sorted format (as required in question)\n- Store the elements as required in array\n\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer,Integer> map=new HashMap<>();\n PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(a[1]==b[1])?b[0]-a[0]:a[1]-b[1]);\n \n //Find count\n for(int n:nums){\n map.put(n,map.getOrDefault(n,0)+1);\n }\n //Sort\n //Insert to pq\n for(int key:map.keySet()){\n pq.add(new int[]{key,map.get(key)});\n }\n \n int[] res=new int[nums.length];\n int idx=0;\n \n while(!pq.isEmpty()){\n int[] tmp=pq.poll();\n while(tmp[1]-->0){\n res[idx]=tmp[0];\n idx++;\n }\n }\n \n return res;\n }\n}\n```\nPlease **upvote**, if you like the solution:)
4
0
[]
3
sort-array-by-increasing-frequency
Java Solution Using HashMap
java-solution-using-hashmap-by-rohitm17-i0fz
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n \n Map<Integer,Integer> map = new HashMap<>();\n \n int L = nums.
rohitm17
NORMAL
2021-06-17T17:41:03.004828+00:00
2021-06-17T17:41:03.004875+00:00
1,075
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n \n Map<Integer,Integer> map = new HashMap<>();\n \n int L = nums.length;\n\t\t\n\t\t//Store numbers with their occurences in Map\n\t\t\n for(int i=0;i<L;i++){\n if(!map.containsKey(nums[i])){\n map.put(nums[i],1);\n }\n else{\n int g = map.get(nums[i]);\n ++g;\n map.put(nums[i],g);\n }\n }\n \n int index=0;\n while(!map.isEmpty()){\n int min=1000,k=0,v=0;\n\t\t\t\n\t\t\t//Select min occuring number and add it in array.\n\t\t\t\n for(Map.Entry<Integer,Integer> entry : map.entrySet()){\n \n \n v=entry.getValue();\n if(v<min){\n k= entry.getKey();\n min=v;\n }\n else if(v==min){\n if(k<entry.getKey()){\n k=entry.getKey();\n }\n }\n }\n while(min!=0){\n nums[index]=k;\n index++;\n min--;\n }\n \n map.remove(k);\n \n }\n return nums;\n \n }\n}\n```\n\nDo let me know in comments if this code can be improved.\nHappy Coding!!!!
4
0
['Java']
2
sort-array-by-increasing-frequency
Python easy solution
python-easy-solution-by-nehakolambe15-qrp9
\n def frequencySort(self, nums: List[int]) -> List[int]:\n nums.sort(reverse=True)\n ans = sorted(nums, key = nums.count)\n return ans
nehakolambe15
NORMAL
2021-05-21T18:20:01.128596+00:00
2021-05-21T18:20:01.128620+00:00
334
false
\n def frequencySort(self, nums: List[int]) -> List[int]:\n nums.sort(reverse=True)\n ans = sorted(nums, key = nums.count)\n return ans
4
0
[]
0
sort-array-by-increasing-frequency
JAVA SIMPLE SOLUTION FASTER THAN 95%
java-simple-solution-faster-than-95-by-s-t4l1
JAVA CODE IS:\n# \n\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer,Integer>map=new HashMap<>();\n for(int val : nu
shivam_gupta_
NORMAL
2021-03-16T15:18:50.087132+00:00
2021-03-16T15:18:50.087195+00:00
502
false
JAVA CODE IS:\n# \n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer,Integer>map=new HashMap<>();\n for(int val : nums)\n map.put(val,map.getOrDefault(val,0)+1);\n PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->b[1]!=a[1] ? a[1]-b[1] : b[0]-a[0]);\n for(Map.Entry<Integer,Integer>m : map.entrySet())\n pq.add(new int[]{m.getKey(),m.getValue()});\n int i=0;\n while(!pq.isEmpty()){\n int a[]=pq.poll();\n while(a[1]-->0)\n nums[i++]=a[0];\n }\n return nums;\n }\n}\n```\nTime : O(nlogn)\nSpace : O(n)\n***PLEASE,UPVOTE IF THIS IS HELPFUL***
4
0
[]
1
sort-array-by-increasing-frequency
Four golang solutions with explanation and images
four-golang-solutions-with-explanation-a-vq1i
The main idea of the first two solutions is to add all the numbers to a matrix of lengths [len(nums)][2] and then sort each frequency of numbers by the max freq
nathannaveen
NORMAL
2021-03-03T21:02:07.160757+00:00
2021-08-20T17:43:49.243697+00:00
246
false
The main idea of the first two solutions is to add all the numbers to a matrix of lengths `[len(nums)][2]` and then sort each frequency of numbers by the max frequency. Suppose two values have the same frequency sort them by the value in descending order. After they are sorted, add all the values back to `nums` and return `nums`.\n\n**This is the sort:**\n\n```\nfor i := 1; i < len(arr); i++ {\n if i >= 1 && ((arr[i-1][0] > arr[i][0]) || \n (arr[i-1][0] == arr[i][0] && arr[i-1][1] < arr[i][1])) {\n arr[i], arr[i-1] = arr[i-1], arr[i]\n i -= 2\n }\n}\n```\n\nThe idea of it is to start at the second item (first if 0 indexed) and then check whether the frequency of the number before the current is greater than the frequency of the current number. This is show like this in the code: `((arr[i-1][0] > arr[i][0])`. Or it checks whether the frequency is the same and whether the current number is greater than the number before the current number, this is show in the code as this: `arr[i-1][0] == arr[i][0] && arr[i-1][1] < arr[i][1]`. If either of these things is true, then switch the current and number before the current element and subtracts `2` from `i`. We subtract `2` from `i` to move back if we have to switch the next current and number before the current numbers. And we subtract `2`, not `1` because the loops `i++` cancel out one of the subtracts. Since we have an `i -= 2`, we have to check whether `i >= 1` because if we don\'t and `i == 0`, we would have an out-of-bounds exception.\n\nIf you dont understand the explaination look at these images:\n\n![image](https://assets.leetcode.com/users/images/e0b432c2-5e05-42c8-951a-d67656b5db84_1614805285.342058.png)\n![image](https://assets.leetcode.com/users/images/5bdfb469-9333-4f88-a75d-c4053c0ce778_1614805285.3951283.png)\n![image](https://assets.leetcode.com/users/images/56115be1-93b3-4a63-85dc-8fd07f852d06_1614805285.5365767.png)\n\n\n\nThe second code has better space complexity because in the first solution we use a `map` of size `len(nums)` and an `array` of size `[len(nums)][2]`. In the second solution we just use an `array` of size `[len(nums)][2]`.\n\n\n\n**Code One:**\n\n``` go\nfunc frequencySort(nums []int) []int {\n m := make(map[int]int)\n arr := [][]int{}\n counter := 0\n\n for _, num := range nums {\n m[num]++\n }\n for i, i2 := range m {\n arr = append(arr, []int{i2, i})\n }\n\n for i := 1; i < len(arr); i++ {\n if i >= 1 && ((arr[i-1][0] > arr[i][0]) || \n (arr[i-1][0] == arr[i][0] && arr[i-1][1] < arr[i][1])) {\n arr[i], arr[i-1] = arr[i-1], arr[i]\n i -= 2\n }\n }\n\n for i := 0; i < len(arr); i++ {\n for j := 0; j < arr[i][0]; j++ {\n nums[counter] = arr[i][1]\n counter++\n }\n }\n\n return nums\n}\n```\n\n**Code Two:**\n\n``` go\nfunc frequencySort(nums []int) []int {\n arr := [][]int{}\n counter := 0\n\n for _, num := range nums {\n contains := false\n\n for _, ints := range arr {\n if ints[1] == num {\n ints[0]++\n contains = true\n break\n }\n }\n\n if !contains {\n arr = append(arr, []int{1, num})\n }\n }\n\n for i := 1; i < len(arr); i++ {\n if i >= 1 && ((arr[i-1][0] > arr[i][0]) ||\n (arr[i-1][0] == arr[i][0] && arr[i-1][1] < arr[i][1])) {\n arr[i], arr[i-1] = arr[i-1], arr[i]\n i -= 2\n }\n }\n\n for i := 0; i < len(arr); i++ {\n for j := 0; j < arr[i][0]; j++ {\n nums[counter] = arr[i][1]\n counter++\n }\n }\n\n return nums\n}\n```\n\nThe idea of the third and fourth solutions are pretty similar to each other. The main difference is that in the third solution we use `sort.Slice`, while in the fourth solution we use a heap.\n\n\n``` go\nfunc frequencySort(nums []int) []int {\n m := make( map[int] int ) // map[val] index in arr\n arr := [][]int{}\n res := []int{}\n \n for _, num := range nums {\n if _, ok := m[num]; !ok {\n arr = append(arr, []int{})\n m[num] = len(arr) - 1\n }\n arr[m[num]] = append(arr[m[num]], num)\n }\n \n sort.Slice(arr, func(i, j int) bool {\n if len(arr[i]) == len(arr[j]) { return arr[i][0] > arr[j][0] }\n return len(arr[i]) < len(arr[j])\n })\n \n for _, a := range arr {\n res = append(res, a...)\n }\n \n return res\n}\n```\n\n``` go\nfunc frequencySort(nums []int) []int {\n m := make( map[int] []int )\n h := &IntHeap{}\n res := []int{}\n for _, num := range nums {\n m[num] = append(m[num], num)\n }\n \n for _, b := range m {\n heap.Push(h, b)\n }\n \n for h.Len() > 0 {\n res = append(res, heap.Pop(h).([]int)...)\n }\n \n return res\n}\n\ntype IntHeap [][]int\n\nfunc (h IntHeap) Len() int { return len(h) }\nfunc (h IntHeap) Less(i, j int) bool { \n if len(h[i]) == len(h[j]) {\n return h[i][0] > h[j][0]\n }\n return len(h[i]) < len(h[j]) \n}\nfunc (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *IntHeap) Push(x interface{}) {\n\t*h = append(*h, x.([]int))\n}\n\nfunc (h *IntHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n```\n
4
0
['Go']
0
sort-array-by-increasing-frequency
C++ sort unordered map
c-sort-unordered-map-by-orderofrootn-ergy
```\nclass Solution {\npublic:\n static bool comp(pair &a,pair &b)\n\t{\n if(a.second==b.second)\n return a.first>b.first;\n\t return a.
orderofrootn
NORMAL
2020-12-07T23:01:16.382715+00:00
2020-12-07T23:01:16.382750+00:00
936
false
```\nclass Solution {\npublic:\n static bool comp(pair<int,int> &a,pair<int,int> &b)\n\t{\n if(a.second==b.second)\n return a.first>b.first;\n\t return a.second<b.second;\n\t}\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int,int> map{};\n for(auto n:nums)\n map[n]++;\n vector<pair<int,int>> vec;\n for(auto p: map)\n vec.push_back(p);\n sort(vec.begin(), vec.end(), comp);\n \n vector<int> ans{};\n for(auto p: vec){ \n while(p.second--)\n\t\t\t\tans.push_back(p.first);\n }\n return ans;\n }\n};
4
1
['C', 'C++']
0
sort-array-by-increasing-frequency
Go solution using sort
go-solution-using-sort-by-sisigogo-fd8n
\nfunc frequencySort(nums []int) []int {\n freq := make(map[int]int)\n for _,v := range nums { freq[v] ++ }\n sort.Slice(nums, func (a,b int) bool {\n
sisigogo
NORMAL
2020-12-07T21:18:41.268946+00:00
2020-12-07T21:18:41.268990+00:00
213
false
```\nfunc frequencySort(nums []int) []int {\n freq := make(map[int]int)\n for _,v := range nums { freq[v] ++ }\n sort.Slice(nums, func (a,b int) bool {\n if freq[nums[a]] == freq[nums[b]] { return nums[a] > nums[b] }\n return freq[nums[a]] < freq[nums[b]]\n })\n return nums\n}\n```
4
0
['Go']
0
sort-array-by-increasing-frequency
Sort Array by Increasing Frequency 🙌📈.
sort-array-by-increasing-frequency-by-vi-76w8
Intuition\nWhen faced with the task of sorting elements based on their frequency, the first thought is to count how often each element appears. Once we know the
vivek_bhurke
NORMAL
2024-07-23T16:47:45.241233+00:00
2024-07-23T16:47:45.241267+00:00
828
false
# Intuition\nWhen faced with the task of sorting elements based on their frequency, the first thought is to count how often each element appears. Once we know the frequency, the problem becomes a matter of sorting based on these frequencies. If two elements have the same frequency, we then use their values to determine their order.\n\n# Approach\n1. Frequency Counting: Use a HashMap to count the frequency of each number in the array.\n2. Boxing for Custom Sorting: Convert the primitive int array to an Integer array. This allows us to use a custom comparator.\n3. Custom Sorting: Sort the array using a custom comparator that sorts primarily by frequency (increasing order) and secondarily by value (decreasing order).\n4. Unboxing: Convert the Integer array back to a primitive int array.\n\n# Complexity\n### Time complexity: $$O(n)$$\n- Counting frequencies takes $$O(n)$$.\n- Sorting the array takes $$O(nlogn)$$.\n- Unboxing the array takes $$O(n)$$.\n\n### Space complexity: $$O(n)$$\n- The frequency map takes $$O(n)$$ space.\n- The boxed array takes $$O(n)$$ space.\n\n# Code\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> mp = new HashMap<>();\n for (int num : nums) {\n mp.put(num, mp.getOrDefault(num, 0) + 1);\n }\n \n Integer[] numsBoxed = Arrays.stream(nums).boxed().toArray(Integer[]::new);\n \n Arrays.sort(numsBoxed, (a, b) -> {\n int freA = mp.get(a);\n int freB = mp.get(b);\n if (freA != freB) {\n return Integer.compare(freA, freB);\n } else {\n return Integer.compare(b, a); \n }\n });\n \n for (int i = 0; i < nums.length; i++) {\n nums[i] = numsBoxed[i];\n }\n \n return nums;\n }\n}\n```
3
0
['Array', 'Hash Table', 'Java']
0
sort-array-by-increasing-frequency
C++||solution using heap||Easy solution
csolution-using-heapeasy-solution-by-bet-2gg8
Intuition\nAs we need to sort elements by their frequency,we can simply use priority queue to do so.\n\nBefore looking at the solution you can try solving https
betagamma
NORMAL
2024-07-23T12:19:37.867765+00:00
2024-07-23T12:19:37.867783+00:00
36
false
# Intuition\nAs we need to sort elements by their frequency,we can simply use priority queue to do so.\n\nBefore looking at the solution you can try solving https://leetcode.com/problems/sort-characters-by-frequency/ with priority queue to be more clear!!\n\n# Approach\nwe can customise cmp class to maintain max heap based on frequencies,then simply push them untill heap get empty and return the ans array.\n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass cmp{\n public:\n bool operator()(pair<int,int> p,pair<int,int> q){\n if(p.second == q.second){\n return p.first < q.first;\n }\n return p.second > q.second;\n }\n};\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n priority_queue<pair<int,int>,vector<pair<int,int>>,cmp>pq;\n unordered_map<int,int>mp;\n for(auto i:nums){\n mp[i]++;\n }\n for(auto &it:mp){\n pq.push({it.first,it.second});\n }\n nums.clear();\n while(!pq.empty()){\n int count = pq.top().second;\n int ele = pq.top().first;\n while(count--){\n nums.push_back(ele);\n }\n pq.pop();\n }\n return nums;\n }\n};\n```
3
0
['Hash Table', 'Heap (Priority Queue)', 'C++']
0
sort-array-by-increasing-frequency
Easy-to-follow..
easy-to-follow-by-nehasinghal032415-1vii
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
NehaSinghal032415
NORMAL
2024-07-23T09:04:01.657557+00:00
2024-07-23T09:04:01.657586+00:00
614
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(2n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n HashMap<Integer,Integer>map=new HashMap<>();\n int n=nums.length;\n for(int i:nums){\n map.put(i,map.getOrDefault(i,0)+1);\n }\n Integer temp[]=new Integer[n];\n for(int i=0;i<n;i++){\n temp[i]=nums[i];\n }\n Arrays.sort(temp, new Comparator<Integer>(){\n public int compare(Integer a,Integer b){\n if(map.get(a)==map.get(b)){\n return b-a;\n }return map.get(a)-map.get(b);\n }\n });\n for(int i=0;i<n;i++){\n nums[i]=temp[i];\n }\n return nums;\n }\n}\n```
3
0
['Array', 'Hash Table', 'Sorting', 'Java']
0
count-almost-equal-pairs-ii
O(N^2) -> O(N * D^4) | Brute force digits diff comparison in Java (barely passes time constraints)
on2-on-d4-brute-force-digits-diff-compar-dz2v
Intuition\n Describe your first thoughts on how to solve this problem. \n\nSimilarly to 3265. Count Almost Equal Pairs I, we can check all pairs for almost-equa
sergey_chebotarev
NORMAL
2024-08-25T04:19:29.291206+00:00
2024-08-25T13:34:18.786926+00:00
2,332
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nSimilarly to [3265. Count Almost Equal Pairs I](/problems/count-almost-equal-pairs-i/), we can check all pairs for almost-equality.\n\nTo keep equlality check fast we want to test only numbers with less than 4 different digits.\n\n**UPD**: fellow C++ users report getting TLE on the same code in case of multiple vector allocations during equality check. A better time complexity is needed to safely pass all tests.\n\n**UPD**: also posted the suggested in hints hash-table version below. It passes all test cases 3 times faster.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nFor any pair of numbers `a` and `b` find the first 4 mismatching digits, keep the unchecked head (or tail) of the numbers as is.\n\nFor the number of differences decide if swaps are possible:\n- `0` differences - no need to swap any digits, return `true`\n- `1` - impossible to swap any pair and get the same number\n- `2`/`3` - possible if the digits match in any order\n- `4` - possble if the mismatched digits match in pairs like in `1234` and `2143`, for `1234` and `2341` 2 swaps aren\'t enough though\n- `5+` - impossible\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N^2)$$ - 2 nested loops over the given array; Equality check is done in $$O(log10(max(nums)))$$ which is limited by 10 iterations for any integer, 4 elements diff array sorting and check takes constant time as well.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code - O(N^2)\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int n = nums.length;\n int result = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n result += almostEqual(nums[i], nums[j]) ? 1 : 0;\n }\n }\n return result;\n }\n\n private boolean almostEqual(int a, int b) {\n int found = 0;\n // first 4 different digits for a and b\n int[] ad = new int[4];\n int[] bd = new int[4];\n while (a > 0 || b > 0) {\n if (a%10 != b%10) {\n ad[found] = a%10;\n bd[found] = b%10;\n found++;\n }\n a /= 10;\n b /= 10;\n if (found == 4) {\n break;\n } \n }\n\n if (found <= 1) {\n return found == 0;\n }\n if (found == 2 || found == 3) {\n Arrays.sort(ad);\n Arrays.sort(bd);\n return a == b && Arrays.equals(ad, bd);\n }\n // found == 4\n // need to get a matching pair first with the same indices,\n // then all digits should match in any order\n for (int i = 0; i < 3; i++) {\n for (int j = i+1; j < 4; j++) {\n if (ad[i] == bd[j] && ad[j] == bd[i]) {\n Arrays.sort(ad);\n Arrays.sort(bd);\n // a == b -> check if the rest digits are equal, found 5+ case\n return a == b && Arrays.equals(ad, bd);\n }\n }\n }\n return false;\n }\n}\n```\n\n# Code - O(N * D^4)\n\nAnother version based on hints from the task.\nComputing all possible 2-swap variations on the fly and counting previously seen variations of the current number.\nIt\'s passes all test cases in **1.6s** -vs- **5.4s** for the O(N^2) approach above.\n\n```java []\nclass Solution {\n static int[] pow10 = {1, 10, 100, 1_000, 10_000, 100_000, 1_000_000};\n static Set<Integer> variations = new HashSet<>();\n\n public int countPairs(int[] nums) {\n // arr[seen_number_variation] = fequency\n Map<Integer, Integer> frequences = new HashMap<>();\n int result = 0;\n for (int value : nums) {\n result += frequences.getOrDefault(value, 0);\n // getting all potential 2-diff variations\n Set<Integer> twoSwapVariations = new HashSet<>();\n for (int oneSwapVariation : new HashSet<>(allOneSwapVariations(value))) {\n twoSwapVariations.addAll(allOneSwapVariations(oneSwapVariation));\n }\n for (int twoSwapVariation : twoSwapVariations) {\n frequences.compute(twoSwapVariation, (k,v) -> (v != null ? v : 0) + 1);\n }\n }\n return result;\n }\n\n private Set<Integer> allOneSwapVariations(int number) {\n variations.clear();\n variations.add(number);\n int maxDigits = 7;\n // try swaping any pair of digits\n for (int i = 0; i < maxDigits; i++) {\n for (int j = i+1; j < maxDigits; j++) {\n int di = (number / pow10[i]) % 10;\n int dj = (number / pow10[j]) % 10;\n if (di == dj) {\n continue;\n }\n // swapping digits i and j\n int diff1variation = number\n - di * pow10[i] + di * pow10[j]\n - dj * pow10[j] + dj * pow10[i];\n variations.add(diff1variation);\n }\n }\n return variations;\n }\n}\n```
19
0
['Java']
11
count-almost-equal-pairs-ii
Video Explanation (Optimising brute force solution using pre-computation)
video-explanation-optimising-brute-force-l2mn
Explanation\n\nClick here for the video\n\n# Code\ncpp []\nconst int N = 1e7;\nint cnt[N];\n\nclass Solution {\n \n inline int MakeNumber (vector<int>& di
codingmohan
NORMAL
2024-08-25T12:46:01.679521+00:00
2024-08-25T12:46:01.679562+00:00
781
false
# Explanation\n\n[Click here for the video](https://youtu.be/t_1vwZbUmzI)\n\n# Code\n```cpp []\nconst int N = 1e7;\nint cnt[N];\n\nclass Solution {\n \n inline int MakeNumber (vector<int>& digits) {\n int ans = 0;\n for (auto it = digits.rbegin(); it != digits.rend(); it ++)\n ans = (ans * 10) + *it;\n return ans;\n } \n \npublic:\n int countPairs(vector<int>& nums) {\n memset(cnt, 0, sizeof(cnt));\n int ans = 0;\n int n = 7;\n vector<int> digits(7, 0);\n \n for (auto i : nums) {\n ans += cnt[i];\n \n int ind = 0;\n while (i) {\n digits[ind ++] = i%10;\n i /= 10;\n }\n while (ind < 7) digits[ind++] = 0;\n \n unordered_set<int> all;\n for (int l1 = 0; l1 < n; l1 ++) {\n for (int r1 = l1+1; r1 < n; r1 ++) {\n swap (digits[l1], digits[r1]); \n all.insert(MakeNumber(digits));\n swap (digits[l1], digits[r1]);\n \n for (int l2 = 0; l2 < n; l2 ++) {\n for (int r2 = l2+1; r2 < n; r2 ++) {\n swap (digits[l1], digits[r1]);\n swap (digits[l2], digits[r2]);\n \n all.insert(MakeNumber(digits));\n \n swap (digits[l2], digits[r2]);\n swap (digits[l1], digits[r1]);\n }\n }\n }\n } \n for (auto it : all) cnt[it] ++;\n }\n return ans;\n }\n};\n```
18
0
['C++']
4
count-almost-equal-pairs-ii
[Python3] Brute Force
python3-brute-force-by-awice-j3ht
Let\'s write a function adj(int) -> set(int) that describes which y are possible to reach from x in at most 2 operations.\n\nNote we only need to care about swa
awice
NORMAL
2024-08-25T04:34:20.353954+00:00
2024-08-25T04:34:20.353979+00:00
693
false
Let\'s write a function `adj(int) -> set(int)` that describes which `y` are possible to reach from `x` in at most 2 operations.\n\nNote we only need to care about swaps in one direction if we sort the array.\n\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, A: List[int]) -> int:\n def adj(x):\n s = list(str(x))\n n = len(s)\n ans = set()\n for i, j in combinations_with_replacement(range(n), 2):\n s[i], s[j] = s[j], s[i]\n for k, l in combinations_with_replacement(range(n), 2):\n s[k], s[l] = s[l], s[k]\n ans.add(int("".join(s)))\n s[k], s[l] = s[l], s[k]\n s[i], s[j] = s[j], s[i]\n return ans\n\n A.sort(reverse=True)\n ans = 0\n count = Counter()\n for x in A:\n ans += count[x]\n for y in adj(x):\n count[y] += 1\n return ans\n```
14
0
['Python3']
3
count-almost-equal-pairs-ii
[Python3] find all neighbors via hashmap
python3-find-all-neighbors-via-hashmap-b-nspg
Find neighbors by one-pair swap. \nNumbers connected with two-pair swaps share neighbors. \n\n\nclass Solution:\n def countPairs(self, nums: List[int]) -> in
ye15
NORMAL
2024-08-25T04:17:34.261180+00:00
2024-08-25T04:17:34.261202+00:00
996
false
Find neighbors by one-pair swap. \nNumbers connected with two-pair swaps share neighbors. \n\n```\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n cnt = Counter(nums)\n freq = defaultdict(list)\n for x, v in cnt.items(): \n freq[x].append((x, v))\n s = list(str(x).zfill(7))\n for j in range(7): \n for k in range(j+1, 7): \n if s[j] != s[k]: \n s[j], s[k] = s[k], s[j]\n cand = int("".join(s))\n freq[cand].append((x, v))\n s[j], s[k] = s[k], s[j]\n ans = defaultdict(int)\n for x, v in freq.items(): \n for (x1, v1) in v: \n ans[x1, x1] = v1*(v1-1)//2\n for (x1, v1), (x2, v2) in combinations(v, 2): \n ans[x1, x2] = v1*v2 \n return sum(ans.values())\n```
11
0
['Python3']
3
count-almost-equal-pairs-ii
Easy Brute force Solution | | C++
easy-brute-force-solution-c-by-loganblue-vie1
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
LOGANBLUE
NORMAL
2024-08-25T04:13:58.355368+00:00
2024-08-25T04:13:58.355399+00:00
2,017
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n string makeDigit(int num, int digits) {\n string s = to_string(num);\n int n = s.size();\n for(int i=0;i<digits-n;i++)\n s = "0" + s;\n return s;\n }\n\n unordered_set<string> makeSwapChanges(int num, int digits) {\n string s = makeDigit(num, digits);\n unordered_set<string> poss;\n poss.insert(s);\n \n for(int i = 0; i < digits; ++i) {\n for(int j = i + 1; j < digits; ++j) {\n swap(s[i], s[j]);\n poss.insert(s);\n for(int i1 = 0; i1 < digits; ++i1) {\n for(int j1 = i1+1; j1 < digits; ++j1) {\n if(s[i1] != s[j1]) {\n swap(s[i1], s[j1]);\n poss.insert(s);\n swap(s[j1], s[i1]);\n }\n }\n }\n swap(s[i], s[j]);\n }\n }\n return poss;\n }\n\npublic:\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n int digits = to_string(*max_element(nums.begin(),nums.end())).size();\n\n unordered_map<string, int> mp;\n int ans = 0;\n for(int i = 0; i < n; ++i) {\n for(const auto& s : makeSwapChanges(nums[i], digits)) {\n if(mp.count(s)) {\n ans += mp[s];\n }\n }\n mp[makeDigit(nums[i], digits)]++;\n }\n\n return ans;\n }\n};\n```
10
1
['C++']
2
count-almost-equal-pairs-ii
Line by line explanation || Initial greedy + Prefix sum + All possible swaps || O(n^2) || Java
line-by-line-explanation-initial-greedy-fu2et
Go down to my code to see explanation line by line.\n\n# Approach\n- Sort the array ascending order to keep a greedy of not dealing with swapping trailing zero
Whusyki
NORMAL
2024-08-25T05:37:29.794977+00:00
2024-08-25T05:37:29.795002+00:00
526
false
# **Go down to my code to see explanation line by line.**\n\n# Approach\n- Sort the array ascending order to keep a greedy of not dealing with swapping trailing zero case.\n- During each iteration in the nums array, we build a prefix sum all elements in nums up to current element (exclusive). Then generate all possible number can create up to 2 swaps for the current element. Then check if each generated number contained in the prefix sum. If yes, increment number of pairs by the frequency we stored in prefix sum.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\nMost number of digit each element can have is up to 7. The reason is because the constraint is strictly less than 10^7 which is 8 digits. So, given 7 digit, there are 7 x 6 = 42 possible swaps. It also requires worst case O(7) to combine all digits into a single number. That means there are 42 possible numbers after up to one swap and takes O(294). We want up to 2 swaps. So iterating each 42 possible numbers, we will get O(42 x 41 x 7) -> O(12054). Altogether, O(12054) + O(294) -> O(12348)\n\nGiven n = 5000, then O(12348) is about O(2.5n) which is basically O(n).\n\n- Space complexity:\nO(n)\n\nThis is simply because of holding a total of possible 42 x 41 -> 1722 numbers which is O(n/4) which basically is O(n) during each iteration of nums array.\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n\n //Initial Greedy\n Arrays.sort(nums);\n\n int pair = 0;\n //Prefix Sum\n Map<Integer, Integer> freq = new HashMap<>();\n\n for (int i = 0; i < nums.length; i++){\n\n //All possible numbers up to 1 swap\n Set<Integer> hold = swap(nums[i]);\n\n //All possible numbers up to 2 swaps\n Set<Integer> total = new HashSet<>();\n\n //Generate all possible numbers up to 2 swaps\n for (int x : hold){\n for (int y : swap(x)){\n total.add(y);\n }\n }\n\n //Check if any of possible swapped number contained in prefix sum\n for (int x : total){\n if (freq.containsKey(x)){\n pair += freq.get(x);\n }\n }\n\n //Build prefix sum\n freq.put(nums[i], freq.getOrDefault(nums[i], 0) + 1);\n }\n\n return pair;\n }\n\n //Generate all possible number with up to 1 additional swap\n private Set<Integer> swap(int n){\n\n //Storing all possible generated numbers\n Set<Integer> s = new HashSet<>();\n\n //Store the original number\n s.add(n);\n\n //Store the digits\n List<Integer> num = new ArrayList<>();\n\n //Split number into digits\n while (n > 0){\n\n //Add the last digit\n num.add(0, n%10);\n\n //Right shift one place\n //Ex: 12345 -> 1234, or 2742 -> 274\n n /= 10;\n }\n\n //Trying out all possible numbers with 1 swap\n for (int i = 1; i < num.size(); i++){\n for (int j = 0; j < i; j++){\n int hold1 = num.get(i);\n int hold2 = num.get(j);\n\n //Swap it\n num.set(i, hold2);\n num.set(j, hold1);\n\n //Combine all digits into one number\n int sol = cal(num);\n\n //Add it to all possible generated numbers\n s.add(sol);\n\n //Swap it back to original number\n num.set(i, hold1);\n num.set(j, hold2);\n }\n }\n\n return s;\n }\n\n //Combined all digits into a number\n private int cal(List<Integer> a){\n\n //Start off with ones digit, then tens, then hundreds, etc\n int ten = 1;\n\n //The final answer\n int ans = 0;\n\n //Start from the ones, which is end of the array\n for (int i = a.size() - 1; i > -1; i--){\n\n //Add the number into the correct digit placement\n ans += ten * a.get(i);\n\n //Increase from ones to tens, or tens to hundreds, etc\n ten *= 10;\n }\n\n return ans;\n }\n}\n```\n\n# Please let me know if you have any question, otherwise please upvote if found helpful? Thanks for reading!
9
0
['Java']
0
count-almost-equal-pairs-ii
Python 3 || 23 lines, dicts || T/S: 75% / 41%
python-3-23-lines-dicts-ts-75-41-by-spau-c033
python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n\n def flip_ch(i: int, j: int)-> None:\n\n if num[i] == num[j]
Spaulding_
NORMAL
2024-08-25T20:06:16.227957+00:00
2024-08-28T04:22:39.814015+00:00
141
false
```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n\n def flip_ch(i: int, j: int)-> None:\n\n if num[i] == num[j]: return\n num[i], num[j] = num[j], num[i]\n\n s = \'\'.join(num)\n\n if next[s] < idx + 1:\n next[s] = idx + 1\n frst[s] += 1\n\n return\n\n\n frst, next, res = defaultdict(int), defaultdict(int), 0\n\n mx = int(log10(max(nums)))+1\n nums = list(map(lambda x: (str(x).rjust(mx, \'0\')), nums))\n\n for idx, num in enumerate(nums):\n\n res+= frst[num]\n frst[num]+= 1\n next[num] = idx + 1\n num = list(num)\n\n for c1, c2 in combinations(range(mx), 2):\n \n flip_ch(c1, c2)\n\n for c3, c4 in combinations(range(c1, mx), 2):\n\n flip_ch(c3, c4)\n num[c3], num[c4] = num[c4], num[c3]\n\n num[c1], num[c2] = num[c2], num[c1]\n \n return res \n```\n[https://leetcode.com/problems/count-almost-equal-pairs-ii/submissions/1368255972/](https://leetcode.com/problems/count-almost-equal-pairs-ii/submissions/1368255972/)\n\nI could be wrong, but I think that time complexity is *O*(*N* * *D* ^4) and space complexity is *O*(*ND*), in which *N* ~ `len(nums)`and *D* ~ maximum number of digits in `nums`.
8
0
['Python3']
0
count-almost-equal-pairs-ii
2 Ways Detailed Description by C++ | Brute Force & Counting By Hash
2-ways-detailed-description-by-c-brute-f-ladq
Intuition\n Describe your first thoughts on how to solve this problem. \nTwo ways to slove the question.\n\n# Approach\n Describe your approach to solving the p
hsu_1997
NORMAL
2024-08-25T07:51:09.653491+00:00
2024-08-25T09:36:25.134030+00:00
511
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTwo ways to slove the question.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Check one by one.\n * Remove duplicates to get the smaller size of data first, any duplicates by n times we get n * (n-1) / 2 pairs by itself.\n * In the non-duplicates set, any two numbers is almost equal, we can get mutiply the times of each showing pairs.\n * For every two numbers, we have 6 different types : {0, 1, 2, 3, 4, 5+} different characters\n * 0 => true\n * 1 => false\n * 2 => If two characters same => true\n * 3 => if three characters same => true\n * 4 => make 4 characters to 2 pairs, if any both pairs same => true\n * 5+ => false\n2. Counting By Hash\n * Sort the nums first by biggest to smallest first, so when we calculate any number we can get by swaping at most 2 times, we can get the smaller number (leading by 0)\n * For each number, we counting duplicated times (c) it showing, and add c * (c-1) / 2 times to answer.\n * For each number, we can get c * count[number] pairs by the previous numbers.\n * Counting every number we can get by swaping at most 2 times, add them to the set.\n * Each number showing in the set, we add c times to the count map\n# Complexity\n- Time complexity: O(N^2 * 8) -> O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N) by remove duplicate and Counting map\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code 1\n```cpp []\nclass Solution {\npublic:\n bool almost_equal(int i, int j){\n if (i == j) return true;\n int s1[8] = {0};\n int s2[8] = {0};\n int cnt = 0;\n while(i || j){\n s1[cnt] = i % 10;\n s2[cnt] = j % 10;\n cnt++;\n i /= 10;\n j /= 10;\n }\n int diff[4];\n cnt = 0;\n for (int i = 0; i < 8; i++){\n if (s1[i] != s2[i]){\n if (cnt == 4) return false;\n diff[cnt++] = i;\n }\n }\n if (cnt == 0) return true;\n if (cnt == 1) return false;\n int a = diff[0];\n int b = diff[1];\n if (cnt == 2) return (s1[diff[0]] == s2[diff[1]]) && (s1[diff[1]] == s2[diff[0]]);\n int c = diff[2];\n if (cnt == 3){\n return (s1[a] == s2[b] && s1[b] == s2[c] && s1[c] == s2[a])|| \n (s1[a] == s2[c] && s1[b] == s2[a] && s1[c] == s2[b]);\n }\n int d = diff[3];\n if (cnt == 4){\n return (s1[a] == s2[b] && s1[b] == s2[a] && s1[c] == s2[d] && s1[d] == s2[c])||\n (s1[a] == s2[c] && s1[c] == s2[a] && s1[b] == s2[d] && s1[d] == s2[b])||\n (s1[a] == s2[d] && s1[d] == s2[a] && s1[b] == s2[c] && s1[c] == s2[b]);\n }\n return false;\n }\n int countPairs(vector<int>& nums) {\n int ans = 0;\n unordered_map<int,int> m;\n vector<int> v;\n for (int i : nums){\n if (m[i] == 0) v.push_back(i);\n m[i]++;\n }\n for (auto i : m) ans += i.second * (i.second - 1) / 2;\n int n = v.size();\n for (int i = 0; i < n; i++){\n for (int j = i + 1; j < n; j++){\n if (almost_equal(v[i], v[j])){\n ans += m[v[i]] * m[v[j]];\n }\n }\n }\n return ans;\n }\n};\n```\n# Code 2\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end(), greater());\n int ans = 0;\n // for (auto i : nums) cout << i << " ";\n // cout << endl;\n unordered_map<int, int> count;\n unordered_set<int> s;\n for (int index = 0; index < n; index++){\n int c = 1;\n while (index + 1 < n && nums[index + 1] == nums[index]) c++, index++;\n ans += c * (c - 1) / 2;\n ans += count[nums[index]] * c;\n string curr = to_string(nums[index]);\n int k = curr.length();\n for (int i = 0; i < k; i++){\n for (int j = i; j < k; j++){\n swap(curr[i], curr[j]);\n for (int a = 0; a < k; a++){\n for (int b = a; b < k; b++){\n swap(curr[a], curr[b]);\n s.insert(stoi(curr));\n swap(curr[a], curr[b]);\n }\n }\n swap(curr[i], curr[j]);\n }\n }\n for (int temp : s) count[temp] += c;\n s.clear();\n }\n return ans;\n }\n};\n```\n# \uD83D\uDD25 If you like the solution, Please Upvote \uD83D\uDD1D\n
4
0
['C++']
2
count-almost-equal-pairs-ii
Java accepted, Python TLE
java-accepted-python-tle-by-chitraksh24-zv8n
Code\njava []\nclass Solution {\n public int countPairs(int[] nums) {\n int ans = 0;\n\n for (int i = 0; i < nums.length; i++) {\n f
chitraksh24
NORMAL
2024-08-25T04:24:46.816280+00:00
2024-08-25T04:24:46.816304+00:00
201
false
# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int ans = 0;\n\n for (int i = 0; i < nums.length; i++) {\n for (int j = i + 1; j < nums.length; j++) {\n String a = String.valueOf(nums[i]);\n String b = String.valueOf(nums[j]);\n\n while (a.length() < b.length()) a = "0" + a;\n while (b.length() < a.length()) b = "0" + b;\n\n int curr = 0;\n int p = -1, q = -1, r = -1, s = -1;\n\n for (int k = 0; k < a.length(); k++) {\n if (a.charAt(k) != b.charAt(k)) {\n curr++;\n if (p == -1) {\n p = k;\n } else if (q == -1) {\n q = k;\n } else if (r == -1) {\n r = k;\n } else if (s == -1) {\n s = k;\n } else {\n break;\n }\n }\n }\n\n if ((curr == 0) || \n (curr == 2 && a.charAt(p) == b.charAt(q) && a.charAt(q) == b.charAt(p)) || \n (curr == 4 && (\n (a.charAt(p) == b.charAt(q) && a.charAt(q) == b.charAt(p) && a.charAt(r) == b.charAt(s) && a.charAt(s) == b.charAt(r)) ||\n (a.charAt(p) == b.charAt(r) && a.charAt(r) == b.charAt(p) && a.charAt(q) == b.charAt(s) && a.charAt(s) == b.charAt(q)) ||\n (a.charAt(p) == b.charAt(s) && a.charAt(s) == b.charAt(p) && a.charAt(r) == b.charAt(q) && a.charAt(q) == b.charAt(r))\n )) ||\n (curr == 3 && (\n (a.charAt(p) == b.charAt(q) && a.charAt(q) == b.charAt(r) && a.charAt(r) == b.charAt(p)) ||\n (a.charAt(p) == b.charAt(r) && a.charAt(q) == b.charAt(p) && a.charAt(r) == b.charAt(q))\n ))) {\n ans++;\n }\n }\n }\n\n return ans;\n }\n}\n```\n```python []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n ans = 0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n a = str(nums[i])\n b = str(nums[j])\n if len(a)<len(b):\n a = \'0\'*(len(b)-len(a)) + a\n else:\n b = \'0\'*(len(a)-len(b)) + b\n curr = 0\n p = -1\n q = -1\n r = -1\n s = -1\n for k in range(len(a)):\n if a[k]!=b[k]:\n curr += 1\n if p==-1:\n p = k\n elif q==-1:\n q = k\n elif r==-1:\n r = k\n elif s==-1:\n s = k\n else:\n break\n if (curr == 2 and a[p] == b[q] and a[q] == b[p]) or (curr==0):\n ans += 1\n if curr == 4:\n if a[p]==b[q] and a[q]==b[p] and a[r]==b[s] and a[s]==b[r]:\n ans += 1\n elif a[p]==b[r] and a[r]==b[p] and a[q]==b[s] and a[s]==b[q]:\n ans += 1\n elif a[p]==b[s] and a[s]==b[p] and a[r]==b[q] and a[q]==b[r]:\n ans += 1\n if curr == 3:\n if a[p]==b[q] and a[q]==b[r] and a[r]==b[p]:\n ans += 1\n elif a[p]==b[r] and a[q]==b[p] and a[r]==b[q]:\n ans += 1\n return ans\n\n```
4
0
['Java', 'Python3']
3
count-almost-equal-pairs-ii
Easy Code With Explanation Javascript and TypeScript
easy-code-with-explanation-javascript-an-nqo3
Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve the problem of counting pairs (i, j) in an array where the numbers are "almost
hashcoderz
NORMAL
2024-08-25T04:22:24.006665+00:00
2024-08-25T04:22:50.471850+00:00
60
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve the problem of counting pairs (i, j) in an array where the numbers are "almost equal," we need to identify pairs where one number can be converted to the other by swapping up to two pairs of digits. Given that this is a combinatorial problem, we will use string manipulations to generate all possible variations of each number by swapping digits.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Generate Variations:\n\n- For each number in the array, generate all possible numbers that can be formed by swapping two digits once and then by swapping two digits twice.\n- We use a set to store these variations to avoid duplicates.\n2. Count Matches:\n\n- Use a map to count occurrences of each number in its zero-padded string form.\n- For each number, look up how many times its variations have been seen before in the map.\n3. Update Map:\n\n- Update the map with the current number\u2019s zero-padded string form to count future occurrences.\n\n## Explanation of Each Function\n1. countPairs(nums: number[]): number:\n\n- Initialize a counter count and a map seen to track occurrences of each number.\n- For each number, generate all possible variations and update the count based on previously seen variations.\n- Update the map with the current number for future reference.\n2. generateVariations(num: number): Set<string>:\n\n- Convert the number to a zero-padded string.\n- Generate all possible variations by swapping each pair of digits once and twice.\n- Return a set of these variations to ensure uniqueness.\n\n3. swap(str: string, i: number, j: number): string:\n\n- Convert the string to an array, swap the characters at indices i and j, and convert it back to a string.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Generating variations involves swapping digits and can be $$O(d^2 )$$ where, $$d$$ is the number of digits in the largest number. Since we generate variations for up to two swaps, the complexity of generating variations can be $$O(d^4 )$$ in the worst case. If n is the number of elements in nums, the total time complexity can be $$O(n\u22C5d^4)$$ where d is the average number of digits in the numbers.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- The space complexity is primarily due to the space required for storing the variations and the map. If there are v unique variations, the space complexity is $$O(v)$$. The map stores occurrences of variations, which also contributes to the space complexity.\n\n# Code\n```typescript []\nfunction countPairs(nums: number[]): number {\n let count = 0;\n const seen = new Map<string, number>();\n\n for (const num of nums) {\n const variations = generateVariations(num);\n for (const variation of variations) {\n count += seen.get(variation) || 0;\n }\n const key = num.toString().padStart(7, \'0\');\n seen.set(key, (seen.get(key) || 0) + 1);\n }\n\n return count;\n}\n\nfunction generateVariations(num: number): Set<string> {\n const str = num.toString().padStart(7, \'0\');\n const variations = new Set<string>([str]);\n\n for (let i = 0; i < str.length; i++) {\n for (let j = i + 1; j < str.length; j++) {\n variations.add(swap(str, i, j));\n }\n }\n\n for (let i = 0; i < str.length; i++) {\n for (let j = i + 1; j < str.length; j++) {\n const swapped = swap(str, i, j);\n for (let k = 0; k < str.length; k++) {\n for (let l = k + 1; l < str.length; l++) {\n variations.add(swap(swapped, k, l));\n }\n }\n }\n }\n\n return variations;\n}\n\nfunction swap(str: string, i: number, j: number): string {\n const arr = str.split(\'\');\n [arr[i], arr[j]] = [arr[j], arr[i]];\n return arr.join(\'\');\n}\n```\n\n## If you like the solution then please upvote........
4
0
['TypeScript']
0
count-almost-equal-pairs-ii
C++ DFS Solution
c-dfs-solution-by-kailam11223-a6j3
Approach\n Describe your approach to solving the problem. \nBasically, dfs the possible swap of each number and increase the count of each visited number. \n\n#
kailam11223
NORMAL
2024-08-25T10:28:05.456499+00:00
2024-08-25T10:28:05.456534+00:00
275
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nBasically, dfs the possible swap of each number and increase the count of each visited number. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(7C2 * 7C2 * n)$$\n\nEach number can expand to 7C2 number(coz num < 1e7), and we at most swap twice. so it takes O(7C2 * 7C2) to explore each possible swap of a number\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ \n\n# Code\n```cpp []\nclass Solution {\nprivate:\n void dfs(vector<int>& digits, set<int>& visited, int x, int step){\n visited.insert(x);\n if(step==2){\n return;\n }\n for(int i = 0; i < digits.size(); ++i){\n for(int j = i+1; j < digits.size(); ++j){\n if(digits[i]==digits[j]) continue;\n int x_ = x + (digits[j]-digits[i])*div[i] + (digits[i]-digits[j])*div[j];\n swap(digits[i], digits[j]);\n dfs(digits, visited, x_, step+1);\n swap(digits[i], digits[j]);\n }\n }\n }\nprivate:\n vector<int> query_digits(int x){\n vector<int> v(MAX_D, 0);\n for(int i = 0; i < MAX_D; ++i){\n v[i] = x%10;\n x/=10;\n }\n return v;\n }\n \n void construct(){\n div = vector<int>(MAX_D, 1);\n for(int i = 1; i < div.size(); ++i){\n div[i] = div[i-1] * 10;\n }\n }\n \n void visit(int x){\n vector<int> digits = query_digits(x);\n set<int> visited;\n dfs(digits, visited, x, 0);\n for(auto v : visited){\n counts[v]++;\n }\n }\n \npublic:\n int countPairs(vector<int>& nums) {\n construct();\n int ret = 0;\n for(auto x: nums){\n ret += counts[x];\n visit(x);\n }\n return ret;\n }\nprivate:\nconst int MAX_D = 7;\nvector<int> div;\nunordered_map<int, int> counts;\n};\n```
3
0
['C++']
0
count-almost-equal-pairs-ii
Beats 100% users || Java || Very Easy Code
beats-100-users-java-very-easy-code-by-d-j4m8
Intuition\nThe problem is to determine how many pairs of numbers in the array can become equal by performing at most two digit swaps on one of the numbers in ea
dhruvbansal153
NORMAL
2024-08-25T04:12:17.225064+00:00
2024-08-25T04:12:17.225082+00:00
655
false
# Intuition\nThe problem is to determine how many pairs of numbers in the array can become equal by performing at most two digit swaps on one of the numbers in each pair. To solve this, we need to:\n\nIdentify Mismatches: Determine the positions where the digits of two numbers differ.\nCheck Swapping Possibilities: Depending on the number of mismatches (0, 2, 3, or 4), check if swapping digits can make the two numbers equal.\n\n# Approach\nCount Pairs:\n\nIterate over each pair of numbers in the nums array.\nFor each pair, use the eql function to determine if they can be made equal with at most two swaps.\nMismatch Identification (eql function):\n\nConvert each number to an array of its digits.\nCompare the digits of the two numbers to find mismatched positions.\nDepending on the number of mismatches:\n0 Mismatches: The numbers are already equal.\n2 Mismatches: Check if a single swap can resolve the differences.\n3 Mismatches: Check if two swaps can resolve the differences by considering all possible swaps.\n4 Mismatches: Check all possible ways to resolve the mismatches with two swaps.\nReturn true if the mismatches can be resolved; otherwise, return false.\nDigit Array Conversion (arr function):\n\nConvert a number into an array of its digits, padding with zeros if needed to ensure an 8-digit representation.\n\n# Complexity\n- Time complexity:\nO(n2)\n\n- Space complexity:\nO(1)\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int n = nums.length;\n int cnt = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (eql(nums[i], nums[j])) {\n \n cnt++;\n }\n }\n }\n return cnt;\n }\n\n public static boolean eql(int x, int y) {\n int[] a1 = arr(x);\n int[] a2 = arr(y);\n int[] mis = new int[4];\n int cnt = 0;\n for (int k = 0; k < 8; k++) {\n if (a1[k] != a2[k]) {\n if (cnt == 4)\n return false;\n mis[cnt] = k;\n cnt++;\n }\n }\n if (cnt == 0)\n return true;\n else if (cnt == 2) {\n return a1[mis[0]] == a2[mis[1]] && a1[mis[1]] == a2[mis[0]];\n \n } else if(cnt==3){\n int a=mis[0];\n int b=mis[1];\n int c=mis[2];\n return (a1[a]==a2[b] && a1[b]==a2[c]&& a1[c]==a2[a])||(a1[a]==a2[c] && a1[c]==a2[b]&& a1[b]==a2[a]);\n }\n else if (cnt == 4) {\n int a=mis[0];\n int b=mis[1];\n int c=mis[2];\n int d=mis[3];\n return(a1[a]==a2[b]&& a1[b]==a2[a] && a1[c]==a2[d]&& a1[d]==a2[c])||\n (a1[a]==a2[c]&& a1[c]==a2[a] && a1[b]==a2[d]&& a1[d]==a2[b])||\n (a1[a]==a2[d]&& a1[d]==a2[a] && a1[b]==a2[c]&& a1[c]==a2[b]);\n } else {\n return false;\n }\n }\n\n public static int[] arr(int num) {\n int[] cnt = new int[8];\n int i = 0;\n while (num > 0) {\n cnt[i] = num % 10;\n num /= 10;\n i++;\n }\n return cnt;\n }\n}\n```
3
0
['Java']
1
count-almost-equal-pairs-ii
💥💥 Beats 100% on runtime and memory [EXPLAINED]
beats-100-on-runtime-and-memory-explaine-6ea1
IntuitionIdentify pairs of numbers in the array that can be made identical by swapping digits up to twice. Since the operation allows swapping digits in each nu
r9n
NORMAL
2025-02-04T02:41:56.169210+00:00
2025-02-04T02:41:56.169210+00:00
6
false
# Intuition Identify pairs of numbers in the array that can be made identical by swapping digits up to twice. Since the operation allows swapping digits in each number, I’ll explore all possible permutations of digits in each number. If two numbers can be made the same after swaps, we count them as a valid pair. # Approach I’ll convert each number into a string with a fixed length (by padding zeros) and generate all unique possible digit permutations by swapping digits. Then, I’ll store these permutations in a map to track how many times they appear, and for each number, check how many of its permutations have already appeared to count valid pairs. # Complexity - Time complexity: O(n * maxLen^2), where n is the number of elements in the array and maxLen is the maximum length of the numbers in the array. This is because for each number, I generate all possible permutations by swapping pairs of digits, which involves nested loops. - Space complexity: O(n * maxLen^2) as well, because I store all possible permutations for each number in a set and count their occurrences in a map. # Code ```kotlin [] class Solution { // Store the maximum number of digits in the numbers private var maxSize = 0 // Convert a number to a string with leading zeros to match maxSize private fun makeDigit(num: Int): String { var s = num.toString() var n = s.length while (n < maxSize) { // Pad with leading zeros until maxSize s = "0$s" n++ } return s } // Generate all unique permutations of a number by swapping digits private fun makeAllSwaps(num: Int): Set<String> { var s = makeDigit(num) val res = mutableSetOf(s) // Perform swaps between each pair of digits for (i in 0 until maxSize) { for (j in i + 1 until maxSize) { s = s.toCharArray().also { swap(it, i, j) }.joinToString("") // Swap two digits res.add(s) // Add the swapped version // Swap other digits in the new permutation for (l in 0 until maxSize) { for (k in l + 1 until maxSize) { if (s[l] != s[k]) { s = s.toCharArray().also { swap(it, l, k) }.joinToString("") // Swap two more digits res.add(s) // Add this new swapped version s = s.toCharArray().also { swap(it, l, k) }.joinToString("") // Revert the swap } } } s = s.toCharArray().also { swap(it, i, j) }.joinToString("") // Revert the initial swap } } return res } // Swap two characters in a char array private fun swap(arr: CharArray, i: Int, j: Int) { val temp = arr[i] arr[i] = arr[j] arr[j] = temp } fun countPairs(nums: IntArray): Int { val n = nums.size maxSize = nums.maxOrNull()?.toString()?.length ?: 0 var ans = 0 val mp = mutableMapOf<String, Int>() // Check all numbers and count how many permutations match previous ones for (i in 0 until n) { for (s in makeAllSwaps(nums[i])) { // If this permutation has been encountered, increase the result count ans += mp.getOrDefault(s, 0) } // Add the zero-padded version of the current number to the map mp[makeDigit(nums[i])] = mp.getOrDefault(makeDigit(nums[i]), 0) + 1 } return ans } } ```
1
0
['Array', 'Hash Table', 'Math', 'String Matching', 'Combinatorics', 'Hash Function', 'Kotlin']
0
count-almost-equal-pairs-ii
Intuitive | generating atmost 2 swaps with optimised recursion
intuitive-generating-atmost-2-swaps-with-iy6o
IntuitionTry to use the generalised generate_atmost_swaps recursive function to generate almost equal numbers for a given number. Use the frequency of each numb
lokeshwar777
NORMAL
2025-01-14T11:12:52.947299+00:00
2025-01-14T11:28:21.967876+00:00
52
false
# Intuition Try to use the generalised `generate_atmost_swaps` recursive function to generate almost equal numbers for a given number. Use the frequency of each number for counting number of almost equal pairs. # Approach I've got TLE when i used the recursive function directly so i tweaked it to prevent a few redundant generations and repeated swaps. I used the `seen` set to store unique generations. Do not forget to normalise each number to 7 digits by padding with `0`s (because each number <= `9999999` < `10^7`) # Complexity - Time complexity: $$O(n*7^2*maxSwaps)$$, here `maxSwaps` is 2 - Space complexity: $$O(n)$$, `n` is no. of unique permutations # Code ```cpp [] class Solution { public: unordered_map<string,int>freq; unordered_set<string>seen; void generate_atmost_swaps(string s,int swaps_left,int start_index){ if(swaps_left<0)return; seen.insert(s); int n=s.size(); for(int i=start_index;i<n;++i){ for(int j=i+1;j<n;++j){ if(s[i]==s[j])continue; swap(s[i],s[j]); generate_atmost_swaps(s,swaps_left-1,i+1); swap(s[i],s[j]); // backtrack } } } int countPairs(vector<int>& nums) { int res=0; for(const int &x:nums){ string num=to_string(x); while(num.size()<7)num='0'+num; // normalise to 7 digits res+=freq[num]; seen.clear(); generate_atmost_swaps(num,2,0); for(const auto &x:seen)freq[x]++; // cout<<num<<" "<<res<<endl; } return res; } }; ``` ```python3 [] class Solution: def countPairs(self, nums: List[int]) -> int: freq=Counter() def generate_atmost_swaps(l,swaps_left,start_index=0): if swaps_left<0:return seen.add(''.join(l)) n=len(l) for i in range(start_index,n): for j in range(i+1,n): if l[i]==l[j]:continue l[i],l[j]=l[j],l[i] generate_atmost_swaps(l,swaps_left-1,i+1) l[i],l[j]=l[j],l[i] # backtrack res=0 for num in nums: num=str(num).zfill(7) # normalise to 7 digits res+=freq[num] seen=set() generate_atmost_swaps(list(num),2) for x in seen:freq[x]+=1 return res ``` ### Observations: 1. `C++` coders : You might get a TLE by passing set as a parameter to the generation function instead try global declaration and clear it using `setName.clear()` method or try reassigning it to an empty set or try `set<T>.swap(setName)`. 2. `Python` coders : You might get a TLE by passing string as a parameter instead consider using a list(reason: less number of str-to-list or list-to-str conversions, mutation friendly). Also consider reinitialising a set using `set()`->$$O(1)$$ instead of `setName.clear()`->$$O(n)$$. ### Note: - This solution is not a fully optimised one but i feed it as intuitive and beginner friendly. Feel free to share your views and optimisations.
1
0
['Hash Table', 'String', 'Recursion', 'String Matching', 'Combinatorics', 'Counting', 'Ordered Set', 'C++', 'Python3']
0
count-almost-equal-pairs-ii
Easiest Solution To ever exist !!!
easiest-solution-to-ever-exist-by-shadan-u175
Intuition\n Describe your first thoughts on how to solve this problem. \nThink about forming all possiblities.\nSee We can perform atmost 2 swaps so form all po
shadan12
NORMAL
2024-08-27T06:04:19.399867+00:00
2024-08-27T06:04:19.399898+00:00
92
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThink about forming all possiblities.\nSee We can perform atmost 2 swaps so form all possible numbers which you can by performing 2 swaps ,\nUse strings to handle data easily\nand then for each possiblity check if it has already occured or not.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1)First convert all the numbers to the maximum length string by converting each number to the number having maxm digits\n2)Try forming all possiblites and check if it has occured previously\nIf yes how many times , add that many times to our answer\n3) Use hash map to maintain how many times the particular string has occured previously.\n\nTADA YOU DID IT !!!.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*d^4)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n //try all possilbilites and form all the strings and check if any of \n //the possible swapping of the current string has already occurred if yes \n //add it to your answer and then increase the current string freq by 1\n string cnvt(int num,int dig){\n string s=to_string(num);\n int n=s.size();\n for(int i=0;i<(dig-n);i++){\n s=\'0\'+s;\n }\n return s;\n }\n unordered_set<string> allPossible(string s){\n int n=s.size();\n unordered_set<string>poss;\n poss.insert(s);\n for(int i1=0;i1<n;i1++){\n for(int j1=i1+1;j1<n;j1++){\n if(s[i1]!=s[j1]){\n swap(s[i1],s[j1]);\n poss.insert(s);\n for(int i2=0;i2<n;i2++){\n for(int j2=i2+1;j2<n;j2++){\n if(s[i2]!=s[j2] && i1!=i2 && j1!=j2){\n swap(s[i2],s[j2]);\n poss.insert(s);\n swap(s[i2],s[j2]);\n }\n }\n }\n swap(s[i1],s[j1]);\n }\n }\n }\n return poss;\n }\n int countPairs(vector<int>& nums) {\n int n=nums.size();\n int maxi=*max_element(nums.begin(),nums.end());\n int digits=to_string(maxi).size();\n\n vector<string>arr;\n for(int i=0;i<n;i++){\n string temp=cnvt(nums[i],digits);\n arr.push_back(temp);\n }\n int ans=0;\n unordered_map<string,int>mp;\n for(int i=0;i<n;i++){\n unordered_set<string>temp=allPossible(arr[i]);\n for(auto it:temp){\n ans+=mp[it];\n }\n mp[arr[i]]++;\n }\n return ans;\n\n }\n};\n```
1
0
['Array', 'Hash Table', 'Combinatorics', 'Ordered Set', 'C++']
2
count-almost-equal-pairs-ii
Python O(N*7^4) = O(2400N) by computing all possible neighbors
python-on74-o2400n-by-computing-all-poss-hkrx
For each n in nums, find all possible neighbors by doing all possible double swaps. (This is a quartic loop BUT the limit of each loop is 7, so it becomes O(24
dkravitz78
NORMAL
2024-08-25T19:51:29.221856+00:00
2024-08-25T19:53:39.704765+00:00
18
false
For each `n` in `nums`, find all possible neighbors by doing all possible double swaps. (This is a quartic loop BUT the limit of each loop is 7, so it becomes `O(2400N)` complexity since `7^4=2401`).\nKeep track of every number seen already (simple hashmap/counter).\nThen for each `n` in `nums`, put `n`, all single swap values possible, and all double swap values possible into a set. There\'s only 2401+49+1 possible at most for each `n` (in reality much less, but that\'s not important since we have a clear upper bound).\nGo through this set of possible neighbors, and if it\'s been seen already in `nums` then increment by the number of times it was seen. \n```\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n C={}\n ret=0\n\n for n in nums:\n n_Neighbors=set([n]) \n L=list(str(n)) # convert to a list so we can swap elements\n while len(L)<7: L=[\'0\']+L # add zeros beforehand\n for i in range(7):\n for j in range(i):\n L[i],L[j]=L[j],L[i]\n n_Neighbors.add(int( \'\'.join(L)))\n for k in range(7):\n for l in range(k):\n L[k],L[l] =L[l],L[k]\n n_Neighbors.add(int( \'\'.join(L)))\n L[k],L[l] =L[l],L[k]\n L[i],L[j]=L[j],L[i]\n \n\n for x in n_Neighbors:\n ret+=C.get(x,0)\n C[n]=C.get(n,0)+1\n return ret\n ```
1
0
[]
0
count-almost-equal-pairs-ii
Easy Solution in c++
easy-solution-in-c-by-luv_mathur-npnn
\n\n# Code\ncpp []\nclass Solution {\npublic:\n \n vector<string> generateSwappedNumbers(string numstr) {\n vector<string> swappedNumbers;\n
Luv_Mathur
NORMAL
2024-08-25T13:27:03.877561+00:00
2024-08-25T13:27:03.877596+00:00
58
false
\n\n# Code\n```cpp []\nclass Solution {\npublic:\n \n vector<string> generateSwappedNumbers(string numstr) {\n vector<string> swappedNumbers;\n int n = numstr.size();\n swappedNumbers.push_back(numstr); \n \n if (n == 1) {\n return swappedNumbers;\n }\n \n \n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n swap(numstr[i], numstr[j]);\n swappedNumbers.push_back(numstr);\n \n \n for (int k = 0; k < n; k++) {\n for (int l = k + 1; l < n; l++) {\n swap(numstr[k], numstr[l]);\n swappedNumbers.push_back(numstr);\n swap(numstr[k], numstr[l]);\n }\n }\n \n swap(numstr[i], numstr[j]); \n }\n }\n \n return swappedNumbers;\n }\n\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n int count = 0;\n unordered_map<int, int> seen;\n sort(nums.begin(), nums.end());\n for (int i = 0; i < n; i++) {\n string numstr = to_string(nums[i]);\n vector<string> swappedNumbers = generateSwappedNumbers(numstr);\n \n \n unordered_map<int, bool> checked; \n for (const string& s : swappedNumbers) {\n int swappedNum = stoi(s);\n if (seen.count(swappedNum) && !checked[swappedNum]) {\n count += seen[swappedNum];\n checked[swappedNum] = true; \n }\n }\n \n \n seen[stoi(numstr)]++;\n }\n\n return count;\n }\n};\n\n```
1
0
['C++']
0
count-almost-equal-pairs-ii
Very Easy Solution in c++
very-easy-solution-in-c-by-luv_mathur-qo3i
\n\n# Code\ncpp []\nclass Solution {\npublic:\n \n vector<string> generateSwappedNumbers(string numstr) {\n vector<string> swappedNumbers;\n
Luv_Mathur
NORMAL
2024-08-25T13:25:55.851962+00:00
2024-08-25T13:25:55.851987+00:00
38
false
\n\n# Code\n```cpp []\nclass Solution {\npublic:\n \n vector<string> generateSwappedNumbers(string numstr) {\n vector<string> swappedNumbers;\n int n = numstr.size();\n swappedNumbers.push_back(numstr); \n \n if (n == 1) {\n return swappedNumbers;\n }\n \n \n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n swap(numstr[i], numstr[j]);\n swappedNumbers.push_back(numstr);\n \n \n for (int k = 0; k < n; k++) {\n for (int l = k + 1; l < n; l++) {\n swap(numstr[k], numstr[l]);\n swappedNumbers.push_back(numstr);\n swap(numstr[k], numstr[l]);\n }\n }\n \n swap(numstr[i], numstr[j]); \n }\n }\n \n return swappedNumbers;\n }\n\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n int count = 0;\n unordered_map<int, int> seen;\n sort(nums.begin(), nums.end());\n for (int i = 0; i < n; i++) {\n string numstr = to_string(nums[i]);\n vector<string> swappedNumbers = generateSwappedNumbers(numstr);\n \n \n unordered_map<int, bool> checked; \n for (const string& s : swappedNumbers) {\n int swappedNum = stoi(s);\n if (seen.count(swappedNum) && !checked[swappedNum]) {\n count += seen[swappedNum];\n checked[swappedNum] = true; \n }\n }\n \n \n seen[stoi(numstr)]++;\n }\n\n return count;\n }\n};\n\n```
1
0
['C++']
0
count-almost-equal-pairs-ii
Why N*N solution giving TLE explained ,How to get rid of TLE with n*n Solution.
why-nn-solution-giving-tle-explained-how-yqq1
Intuition\nHere We have to reduce the number of Operations , as much as Possible.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nH
swayam_wish
NORMAL
2024-08-25T09:59:55.118398+00:00
2024-08-25T10:07:59.900764+00:00
166
false
# Intuition\nHere We have to reduce the number of Operations , as much as Possible.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nHere the N=5000 , Therefore if your solution is having N*N , you are considering to pass the Testcase , but the thing to be noticed is that, N*N = 2.5 * 1e7, atmost 1e8 operations can be performed , so we have truely consicous ,while performing the operation in innermost loop. \nBecause if around 40-50 operations are performed that means that around 5*1e8, operation are performed. Which means it will req 5 sec indeed giving TLE,\n\nHere is my code , which doesn\'t req that much explantion , because the approach almost everyone has understood. The Major part is how to apply In Most Optimised Way.\n\n\nThank you. Please Upvote if you found it Useful. \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int cnt = 0;\n int n = nums.size();\n \n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n int v1 = nums[i];\n int v2 = nums[j];\n \n if (v1 == v2) {\n cnt++;\n continue;\n }\n \n int digits1[4], digits2[4];\n int idx = 0, mismatch = 0;\n \n while (v1 != 0 || v2 != 0) {\n int d1 = v1 % 10;\n int d2 = v2 % 10;\n \n if (d1 != d2) {\n if (mismatch < 4) {\n digits1[mismatch] = d1;\n digits2[mismatch] = d2;\n }\n mismatch++;\n if (mismatch > 4) break;\n }\n \n v1 /= 10;\n v2 /= 10;\n }\n \n if (mismatch == 2) {\n if (digits1[0] == digits2[1] && digits1[1] == digits2[0]) {\n cnt++;\n }\n } else if (mismatch == 3) {\n if ((digits1[0] == digits2[1] && digits2[0] == digits1[2] && digits1[1] == digits2[2]) ||\n (digits1[1] == digits2[0] && digits1[0] == digits2[2] && digits1[2] == digits2[1])) {\n cnt++;\n }\n } else if (mismatch == 4) {\n if ((digits1[0] == digits2[1] && digits1[1] == digits2[0] && \n digits1[2] == digits2[3] && digits1[3] == digits2[2]) || \n (digits1[0] == digits2[2] && digits1[2] == digits2[0] &&\n digits1[1] == digits2[3] && digits1[3] == digits2[1]) ||\n (digits1[0] == digits2[3] && digits1[3] == digits2[0] &&\n digits1[1] == digits2[2] && digits1[2] == digits2[1])\n ) {\n cnt++;\n }\n }\n }\n }\n return cnt;\n }\n};\n\n```
1
0
['C++']
0
count-almost-equal-pairs-ii
[Python3] Simple Solution | Time: O(N * maxLength^4) | Space: O(N)
python3-simple-solution-time-on-maxlengt-hhew
Intuition\n Describe your first thoughts on how to solve this problem. \nWe want to keep track of the count of numbers we\'ve already checked. For the current n
tesfaya
NORMAL
2024-08-25T06:51:28.736458+00:00
2024-08-26T04:27:08.290902+00:00
51
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to keep track of the count of numbers we\'ve already checked. For the current number we are checking, we want to try every single possible swapping of digits, while ensuring we don\'t try duplicate swappings. Then we increase our final answer by the count of numbers we\'ve already visited equal to our swapped number (our almost equal pair). \n# Approach\n<!-- Describe your approach to solving the problem. -->\nMake every number the same length by padding with leading 0\'s. Keep track of counts using a dictionary. Use a set to keep track of which swappings we\'ve already tried. Iterate over all the nums. Add the count of numbers we\'ve visited that are equal to nums[i], or a single swapping of nums[i], or a double swapping of nums[i]. Then add num[i] to our counts.\n\n# Complexity\n- Time complexity: O(N * maxLength^4)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe traverse the list of numbers in O(N), then for each number we perform all the possible swappings in O(maxLength^4)\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe simply keep track of the counts of numbers we\'ve already visited in O(N)\n\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n\n # keep track of count for prior nums seen\n visited = defaultdict(lambda:0)\n # length of longest num\n n = len(str(max(nums)))\n # convert nums to strings\n nums = list(map(str,nums))\n # intialize our answer\n ans = 0\n\n # pad nums till all the same length\n for i in range(len(nums)):\n if len(nums[i]) < n:\n nums[i] = \'0\' * (n-len(nums[i])) + nums[i]\n\n # brute force every swapping possible\n for i in range(len(nums)):\n num = nums[i]\n # keep track of swappings we\'ve already done so we only count once\n done = set()\n # add first the num with no swap & add to \'done\' set\n ans += visited[num]\n done.add(num)\n \n # swap char at indices k & l\n for k in range(len(num)):\n for l in range(k+1,len(num)):\n num2 = list(num)\n num2[k],num2[l]=num2[l],num2[k]\n num2 = \'\'.join(num2)\n # if this swap was not done yet, then try it\n if num2 not in done:\n done.add(num2)\n ans += visited[num2]\n # swap char at indices a & b\n for a in range(len(num2)):\n for b in range(k+1,len(num2)):\n num3 = list(num2)\n num3[a],num3[b]=num3[b],num3[a]\n num3 = \'\'.join(num3)\n # if this swap was not done yet, then try it\n if num3 not in done:\n done.add(num3)\n ans += visited[num3]\n # increment the num we just visited to our dictionary\n visited[num] += 1\n \n return ans\n\n\n```
1
0
['Python3']
0
count-almost-equal-pairs-ii
Easy solution Java
easy-solution-java-by-jangir_yashraj-h19d
\n# Approach\ncount number of unequal pairs and reject if unequal pairs are more than 4 otherwise handle separately for 4,3 or 2 pairs.\n\n# Complexity\n- Time
jangir_yashraj
NORMAL
2024-08-25T06:49:33.543467+00:00
2024-08-25T06:49:33.543494+00:00
66
false
\n# Approach\ncount number of unequal pairs and reject if unequal pairs are more than 4 otherwise handle separately for 4,3 or 2 pairs.\n\n# Complexity\n- Time complexity:\n $$O(n^2)$$\n\n- Space complexity:\n $$O(1)$$ \n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int cnt=0;\n for(int i=0; i<nums.length-1; i++) {\n for(int j=i+1; j<nums.length; j++) {\n int x=nums[i];\n int y = nums[j];\n if(x==y) {\n cnt++;\n continue;\n }\n\n int unequalsDigits=0;\n // for at most 2 swaps, at most 4 unequalDigit pairs are possible,\n // more than 4 will result in numbers inelegible to count \n int[][] d = {\n {-1, -1},\n {-1, -1},\n {-1, -1},\n {-1, -1},\n };\n\n while(x!=0 || y!=0) {\n //remainders ( digits ) to compare\n int r1 = x%10;\n int r2 = y%10;\n\n x/=10;\n y/=10;\n \n if(r1==r2) continue;\n else unequalsDigits++;\n\n\n if(unequalsDigits==1) {\n d[0][0]=r1;\n d[0][1]=r2;\n }\n else if(unequalsDigits==2) {\n d[1][0]=r1;\n d[1][1]=r2;\n \n }\n else if(unequalsDigits==3) {\n d[2][0]=r1;\n d[2][1]=r2;\n \n }\n else if(unequalsDigits==4) {\n d[3][0]=r1;\n d[3][1]=r2;\n \n }else if(unequalsDigits>4) {\n break;\n }\n\n }\n\n if(unequalsDigits>4) continue;\n\n if(unequalsDigits==4) {\n // make pairs of 2 ,2 for the swap to happen\n HashMap<Integer, Integer> map = new HashMap<>();\n\n for(int rw1=0; rw1<3; rw1++) {\n if(map.containsKey(rw1)) continue;\n for(int rw2=rw1+1; rw2<4; rw2++) {\n if(map.containsKey(rw2)) continue;\n int[] a = d[rw1];\n int[] b = d[rw2];\n if(a[0]==b[1] && a[1]==b[0]) {\n map.put(rw1, rw2);\n map.put(rw2, rw1);\n break;\n }\n }\n }\n\n if(map.size()==4) cnt++;\n }else if(unequalsDigits==3) {\n\n // for 2 swaps the numbers will have to interchange with one another twice\n // eg. 3,2,1\n // 1,3,2 swap 1 and 2 first in first row than swap 1 and 3 \n // so for digits of first row we increment frequency of digits\n // and for digts of second row we decrease \n // tha check if the numbers are not adjusted back to zero meaning different digits are present and cannot be made equals after swaps.\n int[] fq = new int[10];\n fq[d[0][0]]++;\n fq[d[1][0]]++;\n fq[d[2][0]]++;\n fq[d[0][1]]--;\n fq[d[1][1]]--;\n fq[d[2][1]]--;\n \n for(int t=0; t<10; t++) {\n if(fq[t]!=0) {\n cnt--;\n break;\n }\n }\n cnt++;\n }\n else if(unequalsDigits==2) {\n // similer to Q 2, just check if the unequalsDigit pairs are swappable to make numbers equal.\n if(d[0][0]==d[1][1] && d[1][0]==d[0][1]) cnt++;\n }\n }\n }\n\n return cnt;\n }\n}\n```
1
0
['Java']
1
count-almost-equal-pairs-ii
Easy Hash map solution (search all the formations)
easy-hash-map-solution-search-all-the-fo-3uom
Intuition\nAs the maximum digits which can be there are 7 as (nums[i] < 10^7)\nthe count of maximum numbers we can form after two swaps are C(n,2) \times C(n,2
Abhishek_exe
NORMAL
2024-08-25T05:14:43.975284+00:00
2024-08-25T05:14:43.975323+00:00
348
false
# Intuition\nAs the maximum digits which can be there are $$7$$ as ($$nums[i] < 10^7$$)\nthe count of maximum numbers we can form after two swaps are $$C(n,2) \\times C(n,2)$$\nwhich will always be less than $$(21 \\times 21)$$\n\nso we can search if the formed number can be found in the array or not\n\n# Approach\n\ncreate a hashmap\ncreate a value result = 0(which will storing result)\n\ntraverse the array from 0 to n-1\n- find all the number which can be formed using max 4 swaps \n- search the found numbers in the hashmap and add the count to the result\n- add the current number to hashmap\n\nNote :- Sort the array in increasing or decreasing order according to the direction of traversal\nbecause 1000 can form 100 but 100 can\'t form 1000\nso if you are traverssing left to right sort in increasing ordere\nand of you are traversing in right to left order sort in decreasing order \n\n\n# Complexity\n- Time complexity:\n $$O(n*21*21)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n void swap(char &a,char &b)\n {\n char t = a;\n a = b;\n b = t;\n }\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n vector<string>numstring;\n sort(nums.begin(),nums.end()); // sorting in increasing order\n for(int i = 0;i<n;i++)\n {\n string str = to_string(nums[i]);\n numstring.push_back(str);\n } \n\n unordered_map<int,int>hash; // declaring the hashmap\n int count = 0;\n for(int i = 0;i<n;i++)\n {\n/* unordered_map seen Hash map is to check \nif we are creating some number twice by swapping operations*/\n unordered_map<int,int>seen; \n int currcand = stoi(numstring[i]);\n string str = (numstring[i]);\n count = count + hash[currcand];\n seen[currcand]++;\n //forming the numbers from str\n for(int index1 = 0;index1<str.size();index1++) \n {\n for(int index2 = index1+1;index2<str.size();index2++)\n {\n swap(str[index1],str[index2]);\n int cand1 = stoi(str);\n if(seen[cand1] == 0)\n {\n count = count + hash[cand1];\n seen[cand1]++;\n }\n\n for(int index3 = 0;index3 < str.size();index3++)\n {\n for(int index4 = index3+1;index4 < str.size();index4++)\n {\n if((index1 == index3) && (index2 == index4))\n continue;\n if((index1 == index4) && (index2 == index3))\n continue;\n \n swap(str[index3],str[index4]);\n int cand2 = stoi(str);\n if(seen[cand2] == 0)\n { \n count = count + hash[cand2];\n seen[cand2]++;\n }\n\n swap(str[index3],str[index4]);\n }\n }\n swap(str[index1],str[index2]);\n }\n }\n hash[currcand] ++;\n }\n return count;\n }\n};\n```\n\n\n# Comment if you have any doubt\n\n
1
0
['Hash Table', 'Sorting', 'C++']
0
count-almost-equal-pairs-ii
Simple solution
simple-solution-by-4di03-nal8
\n# Code\npython3 []\ndef get_all_nums(num, swaps_left, to_be_paired, seen): # get all nums creatabel from num that are in the set of pairs that can be matched\
4di03
NORMAL
2024-08-25T04:59:35.840303+00:00
2024-08-25T04:59:35.840325+00:00
34
false
\n# Code\n```python3 []\ndef get_all_nums(num, swaps_left, to_be_paired, seen): # get all nums creatabel from num that are in the set of pairs that can be matched\n #O(N^5), N = 7\n if swaps_left == 0:\n num_int = int("".join(num))\n #print("L5", num_int)\n if num_int in to_be_paired and num_int not in seen:\n seen.add(num_int)\n return to_be_paired[num_int] # return count of matches\n else:\n return 0\n else:\n\n ans = get_all_nums(num, swaps_left-1,to_be_paired,seen) # do no swap case\n for i in range(len(num)):\n for j in range(i+1,len(num)):\n num[i], num[j] = num[j],num[i] # swap\n ans += get_all_nums(num, swaps_left - 1,to_be_paired, seen)\n num[i], num[j] = num[j],num[i] # backtrack\n return ans \n\n\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n ct = {} # ct of pairs matched for each num in nums\n max_dig_size = 0\n for n in nums:\n #ct[n] = 0\n max_dig_size = max(max_dig_size, len(str(n)))\n\n to_be_paired = collections.Counter(nums)\n ans = 0\n for num in nums:\n lnum = ["0"]* (max_dig_size - len(str(num))) + list(str(num))\n\n # remove form seen so that we dont overcount\n to_be_paired[num] -= 1\n if to_be_paired[num] == 0:\n to_be_paired.pop(num)\n \n ans += get_all_nums(lnum,2, to_be_paired, set([]))\n #print(n, num)\n\n return int(ans)\n\n```
1
0
['Python3']
0
count-almost-equal-pairs-ii
Simple brute force
simple-brute-force-by-warlu-wm7p
Intuition\n Describe your first thoughts on how to solve this problem. \nFind all the possible numbers that can be obtained from each nums[i]\nand check with ot
WARLU
NORMAL
2024-08-25T04:07:17.875978+00:00
2024-08-25T04:07:17.876007+00:00
398
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind all the possible numbers that can be obtained from each nums[i]\nand check with other numbers in nums\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nConvert the nums to an hashmap\nIterate through the nums and find all the posiible numbers that you can generete by swapping at most 2 times, add these generated numbers into another hashmap for avoiding duplicate calculations.\nIterate through the second hashmap and count the number of pairs.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*4096)\nn for itertating through nums and 4096 for genrating all the possible combinations of numbers since the max length of a number can be 8(10000000)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n+4096)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int n=nums.size();\n unordered_map<int,int> mp;\n for(int i:nums) mp[i]++;\n int ans=0;\n for(int i=0;i<n;i++){\n string s1=to_string(nums[i]);\n unordered_map<int,int> mp1;\n mp1[nums[i]]++;\n for(int j=0;j<s1.length();j++){\n for(int k=j+1;k<s1.length();k++){\n swap(s1[j],s1[k]);\n mp1[stoi(s1)]++;\n \n string s2=s1;\n for(int l=0;l<s2.length();l++){\n for(int m=l+1;m<s2.length();m++){\n swap(s2[l],s2[m]);\n mp1[stoi(s2)]++;\n swap(s2[l],s2[m]);\n }\n }\n \n swap(s1[j],s1[k]);\n }\n }\n for(auto& p:mp1){\n ans+=mp[p.first]-(p.first==nums[i]);\n if(to_string(p.first).length()!=to_string(nums[i]).length()){\n ans+=mp[p.first]-(p.first==nums[i]);\n }\n // cout<<p.first<<" "<<ans<<"\\n";\n }\n }\n // cout<<"\\n";\n return ans/2;\n }\n};\n```
1
0
['C++']
1
count-almost-equal-pairs-ii
Simple brute force, C++
simple-brute-force-c-by-jerry5841314-nym9
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
jerry5841314
NORMAL
2024-08-25T04:07:10.132381+00:00
2024-08-25T04:07:10.132415+00:00
173
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n unordered_map<int, int> cnt;\n int res = 0;\n for (int num : nums){\n string s = to_string(num);\n int n = s.size();\n set<int> Set;\n Set.insert(num);\n for (int i = 0; i < n; i++){\n for (int j = i + 1; j < n; j++){\n string s2 = s;\n swap(s2[i], s2[j]);\n Set.insert(stoi(s2));\n for (int k = 0; k < n; k++){\n for (int l = k + 1; l < n; l++){\n string s3 = s2;\n swap(s3[k], s3[l]);\n Set.insert(stoi(s3));\n }\n }\n }\n }\n for (int i : Set)\n res += cnt[i];\n\n cnt[num]++;\n }\n return res;\n }\n};\n```
1
1
['C++']
2
count-almost-equal-pairs-ii
checkPair-2 || C++.
checkpair-2-c-by-rishiinsane-a481
IntuitionWe need to count the pairs of numbers in a list that can become identical by swapping exactly two digits within the numbers, for that we need t to tran
RishiINSANE
NORMAL
2025-02-04T17:39:07.499105+00:00
2025-02-04T17:39:07.499105+00:00
6
false
# Intuition We need to count the pairs of numbers in a list that can become identical by swapping exactly two digits within the numbers, for that we need t to transform each number into a string of uniform length by padding with zeros, and then generate all possible variants of the number obtained by swapping two digits at a time. For each number, we check if any of its swapped variants has appeared before, using a map to keep track of the count of each number (including all its swapped variants). # Approach First, we determine the number of digits required to represent the largest number in the input list, this helps us to reduce the time complexity of the code. For each number in the list, we convert it into a string and generate all possible unique swapped versions by swapping two digits at a time. These variants are generated through nested loops that consider each pair of digits and perform the swaps. Once we have all swapped variants, we check if any of them have been encountered before by looking them up in a map, updating the result by adding the count of previous occurrences. The map mpp stores the frequency of each transformed number, while the set `st` temporarily holds all swapped variants of a number. # Complexity - Time complexity: O(n * d^4) - Space complexity: O(n + d^4) # Code ```cpp [] class Solution { public: int countPairs(vector<int>& nums) { int digits = to_string(*max_element(nums.begin(), nums.end())).size(); int res = 0; unordered_map<string, int> mpp; unordered_set<string> st; string t = "0000000"; for (auto it : nums) { string x = to_string(it); x = t.substr(0, digits - x.size()) + x; st = helper(x, digits); for (auto s : st) { if (mpp.count(s)) res += mpp[s]; } mpp[x]++; } return res; } unordered_set<string> helper(string num, int d) { unordered_set<string> swapped; string s = num; swapped.insert(s); for (int i = 0; i < d - 1; i++) { for (int j = i + 1; j < d; j++) { if (s[i] != s[j]) { swap(s[i], s[j]); swapped.insert(s); } for (int x = 0; x < d - 1; x++) { for (int y = x + 1; y < d; y++) { if (s[x] != s[y]) { swap(s[x], s[y]); swapped.insert(s); swap(s[x], s[y]); } } } swap(s[i], s[j]); } } return swapped; } }; ```
0
0
['C++']
0
count-almost-equal-pairs-ii
C++ brute force
c-brute-force-by-dongdang7777-dhad
IntuitionApproachComplexity Time complexity: n*digit^4 Space complexity: Code
dongdang7777
NORMAL
2024-12-25T06:45:19.944024+00:00
2024-12-25T06:45:19.944024+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: n*digit^4 - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: unordered_set<int> get(int n) { string s=to_string(n); unordered_set<int> res; for (int i1=0;i1<s.size();i1++){ for(int j1=i1;j1<s.size();j1++){ swap(s[i1],s[j1]); for(int i2=0;i2<s.size();i2++){ for(int j2=i2;j2<s.size();j2++){ swap(s[i2],s[j2]); res.insert(stoi(s)); swap(s[i2],s[j2]); } } swap(s[i1],s[j1]); } } return res; } int countPairs(vector<int>& nums) { sort(nums.begin(),nums.end()); unordered_map<int,int> past; int res=0; for (auto x:nums){ unordered_set<int> g=get(x); for(auto y:g) res+=past[y]; past[x]++; } return res; } }; ```
0
0
['C++']
0
count-almost-equal-pairs-ii
Brute Force w/ optimizations
brute-force-w-optimizations-by-ivangnilo-7ofz
IntuitionThe key insight is that two numbers are "almost equal" if we can make them equal by swapping digits within one number up to 2 times. Therefore, for eac
ivangnilomedov
NORMAL
2024-12-21T16:11:51.747310+00:00
2024-12-21T16:11:51.747310+00:00
6
false
# Intuition The key insight is that two numbers are "almost equal" if we can make them equal by swapping digits within one number up to 2 times. Therefore, for each number, we need to generate all possible permutations achievable with ≤2 swaps and check if any previous numbers could match them. # Approach 1. Process numbers sequentially, for each number: - Add count of already seen numbers that match current number - Generate all permutations achievable with ≤2 swaps: * Pad with zeros for uniform processing * Try first swap, then for each first swap try all possible second swaps * Store unique permutations in a set - Add all permutations to frequency map for future matches 2. Use smart counting technique: - Only check matches with previous permutations of preceding numbers - Track permutation frequencies in a hash map # Complexity - Time complexity: $$O(n * l^4)$$ where n is array length and l is max digits (7) * For each number (n) we try all possible first swaps (l^2) and for each try all second swaps (l^2) - Space complexity: $$O(n * l^4)$$ * Store up to l^4 permutations for each of n numbers * In practice much less due to duplicate elimination # Code ```cpp [] class Solution { public: int countPairs(vector<int>& nums) { unordered_map<int, int> num2count; int res = 0; for (int idx = 0; idx < nums.size(); ++idx) { /** Proof of correctness for checking only preceding numbers: * 1. Consider any valid pair (A,B) where A and B are almost equal * 2. When we process B, all permutations of A are already in num2count * 3. If B can become A through ≤2 swaps, then A is one of B's permutations * 4. Therefore, when processing B, we'll find A in num2count * 5. Conversely, when we processed A, we didn't need B's future permutations * because we'll catch this pair when we reach B */ res += num2count[nums[idx]]; // Add count of existing numbers that match current number string decimal = to_string(nums[idx]); /** Pad number with leading zeros to handle all cases uniformly * This ensures we don't miss any valid permutations when swapping digits * 1. When we swap digits, any zero moved from padding zone to significant digits * creates a number impossible to get from original (e.g. 123 -> 012) * 2. Such numbers can never match with real numbers from input because: * - Input contains only positive integers (no leading zeros) * - Any real number from input, when permuted legally (≤2 swaps), * can't produce a leading zero as all its digits are significant * 3. Therefore, padding adds impossible permutations but they never match * with valid numbers, so they don't affect the final count */ int need_extrasize = max<int>(0, kMax10Pow - decimal.length()); decimal.resize(decimal.length() + need_extrasize); for (int i = decimal.length(); i - need_extrasize >= 0; --i) decimal[i] = decimal[i - need_extrasize]; for (int i = 0; i < need_extrasize; ++i) decimal[i] = '0'; unordered_set<int> permutations; // Unique permutations permutations.insert(nums[idx]); const int l = decimal.length(); for (int i = 0; i < l - 1; ++i) { for (int j = i + 1; j < l; ++j) if (decimal[i] != decimal[j]) { swap(decimal[i], decimal[j]); permutations.insert(stoi(decimal)); for (int p = 0; p < l - 1; ++p) { for (int q = p + 1; q < l; ++q) if (decimal[p] != decimal[q]) { swap(decimal[p], decimal[q]); permutations.insert(stoi(decimal)); swap(decimal[p], decimal[q]); } } swap(decimal[i], decimal[j]); } } for (int perm : permutations) ++num2count[perm]; } return res; } private: static constexpr int kMax10Pow = 7; }; ```
0
0
['C++']
0
count-almost-equal-pairs-ii
Solution
solution-by-teut-zetp
IntuitionImproved code for existing solution. Just generate all strings that can be made by swapping at most twice for each num. Count map stores the count of a
teut
NORMAL
2024-12-16T07:09:40.718201+00:00
2024-12-16T07:13:39.500390+00:00
4
false
# Intuition\nImproved code for existing solution. \nJust generate all strings that can be made by swapping at most twice for each num.\nCount map stores the count of a number.\nWe add the counts of each neighbour to total. Why?\nSo, at each step you are adding increasing the count of a num present in ""nums"" only and not the neighbour. You have to check if any neighbour of the current num is already seen previously.\nNeighbour is the string that you can get within 2 swaps.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \n- Space complexity:\n$$O(n)$$\n\n# Code\n```python3 []\n\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n total = 0\n count_map = Counter() # counts of neighbours of some like {"123545": 3}\n \n for num in nums:\n num = str(num).zfill(7) # padd 0\'s to front make len 7, see constraints\n neighbours = set([num]) \n num_list = list(num) # [1,2,3,5,4,5]\n \n for i in range(7):\n for j in range(i):\n num_list[i], num_list[j] = num_list[j], num_list[i] # swap op 1\n neighbours.add("".join(num_list))\n \n for k in range(7):\n for l in range(k):\n num_list[k], num_list[l] = num_list[l], num_list[k]# swap op 2\n neighbours.add("".join(num_list))\n num_list[k], num_list[l] = num_list[l], num_list[k] # undo swap op 2\n \n num_list[i], num_list[j] = num_list[j], num_list[i] # undo swap op 1\n\n for neighbour in neighbours: # slighly complex to understand and come up with part in my opinion, maybe easy for others\n total += count_map[neighbour]\n \n count_map[num] += 1\n return total\n\n```
0
0
['Python3']
0
count-almost-equal-pairs-ii
Permutation Set Intersections, Sliding Window | O(𝑛²+𝑛𝑚⁴), O(𝑛𝑚⁴) | 28.00%, 5.33%
permutation-set-intersections-sliding-wi-xamf
See brute force method used for a simpler variant of this problem in 3265. Count Almost Equal Pairs I where number of swaps is at most once.\n# Intuition\n Desc
Winoal875
NORMAL
2024-12-04T05:15:18.135475+00:00
2024-12-04T05:15:18.135503+00:00
6
false
*See brute force method used for a simpler variant of this problem in [3265. Count Almost Equal Pairs I](https://leetcode.com/problems/count-almost-equal-pairs-i/solutions/6110920/brute-force-o-o-35-77-96-50/) where number of swaps is at most once.*\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem extends the concept of "almost equal" by allowing up to two swaps of digits within either numbers. With two swaps, there may be up to 4 digit mismatches, even 3 mismatches, as a single digit may be swapped twice with different digits. This sheer number of possible combinations means a brute-force comparison method will be inefficient.\n\nOur approach **precomputes all possible \'almost equal\' permutations** of every number, and uses **set intersections** to count the number of previous visited numbers that are almost equal to the current number, while leveraging **digit-padding to handle leading zeros** for consistent string manipulation. This approach combines an <ins>optimized brute force</ins> for precomputing all permutation sets, with a <ins>greedy sliding window</ins> to count pair overlaps with visited numbers.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Convert all numbers to 7-digit strings with leading zeros (if necessary).\n- Generate and store in a set "almost equal" variants for each number, considering:\n - No swaps.\n - One swap (2 mismatches).\n - Two swaps.\n - 2 separate pairs to swap (4 mismatches)\n - 2 overlapping pairs to swap (3 mismatches)\n- Use a sliding set approach to count valid pairs:\n - Maintain a counter `left_set` of previously seen numbers.\n - For each new number, find the intersection of its "almost equal" set with `left_set`.\n - Increment the count by the sum of occurrences of the intersecting elements in `left_set`.\n- Update `left_set` with the current number.\n# Complexity\n*where $n$ is the number of elements in `nums`, and $m$ is the maximum number of digits per number.*\n- **Time complexity: O(\uD835\uDC5B\xB2+\uD835\uDC5B\uD835\uDC5A\u2074)**\nFor precomputing every possible almost equal variant of all $n$ numbers of maximum $m$ digits, and comparing these variants with all $n$ numbers to find number of overlaps.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- **Space complexity: O(\uD835\uDC5B\uD835\uDC5A\u2074)**\nFor storing all possible almost equal variant of every number of maximum $m$ digits in `nums`.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n| Runtime | Memory |\n| -------- | ------- |\n| **6776** ms &#124; beats **28.00%** | **119.82** MB &#124; beats **5.33%**|\n```python3 []\nclass Solution:\n def countPairs(self, nums: list[int]) -> int:\n def convert_to_len7(s:str) -> str:\n s = s.zfill(7)\n return s\n # given 1 <= nums[i] < 10^7, nums[i] has to be 7 digits or less\n n = len(nums)\n output = 0\n list_of_sets = []\n for i in range(n):\n num = str(nums[i])\n num = convert_to_len7(num)\n nums[i] = num\n possible_1,possible_2 = set(),set()\n\n # No swaps\n possible_2.add(num)\n # 1 swap\n for j in range(6):\n for k in range(j+1,7):\n if num[j] != num[k]:\n p = num[:j] + num[k] + num[j+1:k]+ num[j] + num[k+1:]\n if p not in possible_1:\n possible_1.add(p)\n possible_2.add(p)\n # 2 swaps\n for x in range(6):\n for y in range(x+1,7):\n if p[x] != p[y]:\n newnum = p[:x]+p[y]+p[x+1:y]+p[x]+p[y+1:]\n possible_2.add(newnum)\n\n list_of_sets.append(possible_2)\n\n from collections import Counter\n left_set = Counter({nums[0]:1})\n # print(left_set)\n for i in range(1,n):\n common_elements = list_of_sets[i].intersection(left_set.keys())\n output += sum(left_set[element] for element in common_elements)\n left_set.update({nums[i]:1})\n\n return output\n```\n# Detailed Approach\n1. Preprocessing:\n - Convert each number to a 7-digit string using `zfill()`.\n - Generate all "almost equal" variants for each number to store in set `possible_2`:\n - No swaps: Add the number itself to the set.\n - One swap: For every pair of positions (`i`, `j`) in the string:\nSwap digits and add the result to the set.\n - Two swaps:\n - For each one-swap variant, for every new pair of positions (`x`, `y`), swap digits again and add the result.\n - Append set `possible_2` to `lists_of_sets`, which will contain \'almost equal variants\' for all corresponding numbers in `nums`.\n2. Count Valid Pairs:\n - Initialize an empty counter `left_set` to store occurrences of previously seen numbers.\n - For each number\'s set of variants:\n - Find the intersection of its set with the keys in `left_set` [creates a set `common_elements` of numbers that appear in both `left_set` (as keys), and in `list_of_sets[i]` (ie.`possible_2`)].\n - For each overlapping variant, add the count (value) from `left_set` to the result `output`.\n - Update `left_set` by adding 1 count to the base number (`nums[i]` visited.\n3. Return Result:\n - The final count `output` represents the number of valid pairs.\n\n# Detailed Complexity Breakdown\n*where $n$ is the number of elements in `nums`, and $m$ is the maximum number of digits per number.*\n### Time Complexity: $O(\uD835\uDC5B^2 + nm^4)$\n1. Preprocessing:\n - $O(n)$ time is taken in the outer loop to process $n$ base numbers in `nums`. For each number:\n - Padding is performed in $O(m)$ to represent the number as a m-digit string. \n - Zero Swap variants adds the original number to the set taking $O(1)$ time.\n - To find One Swap variants, each pair of digits `(i,j)` is compared, taking $O(m^2)$ time.\n - To find Two Swaps variants, for each one-swap results, the digits are iterated through again to compare each pair of digits `(x,y)`, taking $O(m^2)$ time.\n - Therefore the time taken to preprocess and generate "almost equal" variants for all numbers is $O(n(m+1+m^4)) = O(nm^4)$.\n2. Pair Counting:\n - $n$ elements are processed to find the count of intersections between its variants and previously visited numbers, the outer loop takes $O(n)$ time.\n - In the inner loop:\n - From the preprocessing step, each set of variants has a maximum size of $O(m^4)$.\n - `left_set` contains up to $n$ elements.\n - Set intersection takes $O(\\min(len(set1), len(set2))) = O(\\min(m^4, n))$ time. For simplicity (overestimate), we treat this as $O(n + m^4)$.\n - Therefore, the time taken for the pair counting step is $O(n(n+m^4)) = O(n^2 + nm^4)$\n3. Overall Time Complexity:\n - Combining preprocessing and counting, time complexity is $O(nm^4 + n^2 + nm^4) = O(n^2+nm^4)$\n\n### Space Complexity: $O(nm^4)$\n1. Storage for Variant Sets:\n - Each number generates a set with up to $m^4$ elements, hence needing $O(nm^4)$ space for $n$ numbers.\n2. Counter dictionary `left_set`:\n - Tracks the counts of up to $$n$$ base numbers, taking $O(n)$ space.\n3. Intersection set `common_elements`:\n - Contains up to $\\min(m^4, n)$ intersecting elements between the variant set and `left_set`.\n\n# Best, Worst, and Average Case Analysis\n### Time Complexity\n1. Best-case: $O(n^2)$\n - When every number has no almost equal variant other than itself (eg. the number \'7777777\'), so all $O(m^4)$ operations are reduced to $O(1)$.\n2. Worst-case: $O(n^2+nm^4)$\n - Every number has no repeating digits (eg. \'1234567\'), meaning there are the full $m^4$ almost equal variants.\n3. Average-case: $O(n^2+nm^4)$\n - On average, the every number may contain a mix of repeating and non-repeating digits (eg. \'1122345\'), thus having less than but still significantly close to $m^4$ almost equal variants.\n\n### Space Complexity\nIn all cases, $O(n)$ space is still required for `left_set`.\n1. Best-case: $O(2n)$ = $O(n)$\n - When every number has no almost equal variant other than itself (eg. the number \'7777777\'), so all $O(m^4)$ operations are reduced to $O(1)$, and there will be $n$ almost equal variants (equal \'variants\' of $n$ numbers).\n2. Worst-case: $O(n+nm^4+\\min(n,m^4))$ = $O(nm^4)$\n - Every number has no repeating digits (eg. \'1234567\'), meaning there are the full $m^4$ almost equal variants.\n3. Average-case: $O(n+nm^4+\\min(n,m^4))$ = $O(nm^4)$\n - On average, the every number may contain a mix of repeating and non-repeating digits (eg. \'1122345\'), thus having less than but still significantly close to $m^4$ almost equal variants.\n### Summary\n| Scenario | Time Complexity | Space Complexity |\n| - | - | - |\n| Best Case | $O(n^2)$ | $O(n)$ |\t\n| Worst Case | $O(n^2+nm^4)$ | $O(nm^4)$ |\n| Average Case | $O(n^2+nm^4)$ | $O(nm^4)$ |\n***\nCheck out my solutions to other problems here! \uD83D\uDE03\n*https://leetcode.com/discuss/general-discussion/5942132/my-collection-of-solutions*\n***
0
0
['Sliding Window', 'Combinatorics', 'Counting', 'Python3']
0
count-almost-equal-pairs-ii
Generate swaps for each and check.
generate-swaps-for-each-and-check-by-til-rek3
Key takeaway is to sort the array in descending order because we can swap the digits of bigger number to get the smaller number but not vice versa.\n\nIn the ge
Tilak27
NORMAL
2024-11-04T19:48:26.175668+00:00
2024-11-04T19:48:26.175734+00:00
7
false
Key takeaway is to sort the array in descending order because we can swap the digits of bigger number to get the smaller number but not vice versa.\n\nIn the getswap function I have used an unordered_set because duplicate numbers can be made from 1 swap and 2 swaps. \n\nIf the current nums[i] value is present in the map that means some number/s on being swapped (or not being swapped) give nums[i], therefore add the value of m[nums[i]] to the total count.\n\n# Complexity\n- Time complexity: O(n * 32 * 32 + nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * 32 * 32)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n void getswap(int x, unordered_map <int, int> &m) {\n\n string s = to_string(x);\n\n int n = s.size();\n\n unordered_set <int> st;\n\n\n for(int i = 0; i < n; i++) {\n\n for(int j = i + 1; j < n; j++) {\n\n if(s[i] == s[j]) continue;\n\n swap(s[i], s[j]);\n\n // m[stoi(s)]++;\n\n st.insert(stoi(s));\n\n for(int k = 0; k < n; k++) {\n\n for(int l = k + 1; l < n; l++) {\n\n\n if((k == i and l == j) or s[k] == s[l]) continue;\n\n swap(s[k], s[l]);\n\n // m[stoi(s)]++;\n st.insert(stoi(s));\n\n swap(s[k], s[l]);\n\n }\n\n }\n\n swap(s[i], s[j]);\n\n \n }\n }\n\n for(auto i: st) {\n\n m[i]++;\n }\n\n\n }\n\n\n int countPairs(vector<int>& nums) {\n\n unordered_map <int, int> m;\n\n int cnt = 0;\n\n sort(nums.begin(), nums.end(), greater <int>());\n\n for(int i = 0; i < nums.size(); i++) {\n\n if(m.find(nums[i]) != m.end()) {\n\n cnt += m[nums[i]];\n }\n\n // else {\n\n m[nums[i]]++;\n\n getswap(nums[i], m);\n // }\n\n\n }\n\n // for(auto i: m) {\n\n // cout << i.first << ": " << i.second << endl;\n // }\n\n return cnt;\n \n }\n};\n```
0
0
['Array', 'Hash Table', 'Sorting', 'C++']
0
count-almost-equal-pairs-ii
Clean Python Solution
clean-python-solution-by-ramizdundar-jh9o
Code\npython3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n pten = [1, 10, 100, 1000, 10000, 100000, 1000000]\n\n def s
ramizdundar
NORMAL
2024-10-30T19:15:44.912851+00:00
2024-10-30T19:15:44.912875+00:00
5
false
# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n pten = [1, 10, 100, 1000, 10000, 100000, 1000000]\n\n def swap(num, i, j):\n numi = (num // pten[i]) % 10\n numj = (num // pten[j]) % 10\n\n num += numi * (pten[j] - pten[i])\n num += numj * (pten[i] - pten[j])\n\n return num\n\n @cache\n def almostEquals(num):\n equals = {num}\n for i, j in itertools.combinations(range(7), 2):\n n = swap(num, i, j)\n equals.add(n)\n for k, l in itertools.combinations(range(i + 1, 7), 2):\n equals.add(swap(n, k, l))\n\n return equals\n\n d = defaultdict(int)\n tot = 0\n for n in nums:\n for e in almostEquals(n):\n tot += d[e]\n\n d[n] += 1\n\n return tot\n\n```
0
0
['Python3']
0
count-almost-equal-pairs-ii
C++ Solution with Explanation and Time Optimizations
c-solution-with-explanation-and-time-opt-kapq
Approach\nSame as other solutions. Important points:\n1. Think of 0 as a valid digit. Variations of "1" should include 10,100,1000,etc.\n2. Then, you can think
lilyx998
NORMAL
2024-09-25T05:26:10.625042+00:00
2024-09-25T05:26:10.625077+00:00
15
false
# Approach\nSame as other solutions. Important points:\n1. Think of 0 as a valid digit. Variations of "1" should include 10,100,1000,etc.\n2. Then, you can think of equality as symmetric. 1=10 and 10=1.\n3. (c++) Don\'t allocate dynamically sized things in the for loops. The `allOneSwapVariations` thing in the main Java solution caused me to TLE.\n4. (c++) Use a statically allocated `int[]` for tracking the frequency of each number. Using an `unordered_map` caused me to TLE.\n\n# Complexity\n- Time complexity: O(N * D^4)\n\n- Space complexity:1e7\n\n# Code\n```cpp []\ntypedef vector<int> vi;\ntypedef pair<int, int> pii;\n#define ll long long\n#define uoset unordered_set\n#define pb push_back\n#define mp make_pair\n#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))\n#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))\n#define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a))\n#define FOREACH(a, b) for (auto&(a) : (b))\n#define REP(i, n) FOR(i, 0, n)\n#define REPN(i, n) FORN(i, 1, n)\n#define dbg(x) cout << (#x) << " is " << (x) << endl;\n#define dbg2(x, y) cout << (#x) << " is " << (x) << " and " << (#y) << " is " << y << endl;\n#define dbgarr(x, sz) \\\n for (int asdf = 0; asdf < (sz); asdf++) cout << x[asdf] << \' \'; \\\n cout << endl;\n#define dbgarr2(x, rose, colin) \\\n for (int asdf2 = 0; asdf2 < rose; asdf2++) { \\\n dbgarr(x[asdf2], colin); \\\n }\n#define dbgitem(x) \\\n for (auto asdf = x.begin(); asdf != x.end(); asdf++) cout << *asdf << \' \'; \\\n cout << endl;\n\n// The largest number in nums is 9999999, i.e. we don\'t need to consider numbers with > 7 digits\nconst int pows[8]={1,10,100,1000,(int)1e4,(int)1e5,(int)1e6}, MAXN=1e7; // pows[i]=10^i\nint frqs[MAXN];\nclass Solution {\n public: int countPairs(vector < int > & nums) {\n int res = 0;\n memset(frqs, 0, sizeof(frqs));\n for (int num: nums) {\n res += frqs[num];\n uoset < int > allVariatons; // using 0, 1, or 2 swaps\n REP(i, 7) FOR(j, i + 1, 7) { // Swap digits i < j.\n int di = num / pows[i] % 10, dj = num / pows[j] % 10, x = num - di * pows[i] + dj * pows[i] - dj * pows[j] + di * pows[j]; // 1 swap variation\n allVariatons.insert(x);\n REP(i2, 7) FOR(j2, i2 + 1, 7) { // Swap digits i2 < j2 in x.\n int di2 = x / pows[i2] % 10, dj2 = x / pows[j2] % 10;\n allVariatons.insert(x - di2 * pows[i2] + dj2 * pows[i2] - dj2 * pows[j2] + di2 * pows[j2]); // two swap variation\n }\n }\n for (int variation: allVariatons) frqs[variation]++;\n }\n return res;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Optimized brute-force
optimized-brute-force-by-votrubac-3z3e
We count numbers using a hash map n.\n\nBut first, we generate valid permutatins (one or two swaps) for each number, and check if we have matches in the hash ma
votrubac
NORMAL
2024-09-03T07:23:04.444872+00:00
2024-09-03T07:54:58.956381+00:00
25
false
We count numbers using a hash map `n`.\n\nBut first, we generate valid permutatins (one or two swaps) for each number, and check if we have matches in the hash map. Note that we also need to de-duplicate permutations to avoid double-counting.\n\nNow, we want to make it as fast as possible:\n> The runtime limit for C++, I believe, is 3,000 ms, and the solution below is AC with 300 ms runtime.\n- Avoid `int` to `string` conversions - we `swap` two digits in integer.\n- Use global `vis` array for de-duplication. We can use a trick to avoid re-initialization by storing the index `id` of the number being processed.\n- Check if the first swap resulted in a different number, and only do the second swap if it does. \n\n**C++**\n```cpp\nint vis[10000000], pw[] = {1, 10, 100, 1000, 10000, 100000, 1000000};\nint swap(int n, int i, int j) {\n return n + n / pw[i] % 10 * (pw[j] - pw[i]) + n / pw[j] % 10 * (pw[i] - pw[j]); \n}\nclass Solution {\npublic:\nunordered_map<int, int> m; \nint count(int n, int i) {\n if (exchange(vis[n], i + 1) != i + 1)\n if (auto it = m.find(n); it != end(m))\n return it->second;\n return 0;\n}\nint countPairs(vector<int>& nums) {\n int res = 0;\n for (int id = 0; id < nums.size(); ++id) {\n for (int i = 0; i < 7; ++i)\n for (int j = i; j < 7; ++j) {\n int n1 = swap(nums[id], i, j);\n res += count(n1, id);\n if (n1 != nums[id])\n for (int k = i + 1; k < 7; ++k)\n for (int l = k + 1; l < 7; ++l)\n res += count(swap(n1, k, l), id); \n }\n ++m[nums[id]];\n }\n return res;\n}\n};\n```
0
0
['C']
0
count-almost-equal-pairs-ii
DP with enumeration clean code
dp-with-enumeration-clean-code-by-dmitri-wd4b
\nint countPairs(vector<int>& nums) {\n const int maxDigits = size(to_string(*ranges::max_element(nums)));\n vector<string> sNums;\n for (const auto v
dmitrii_bokovikov
NORMAL
2024-09-01T14:41:37.397854+00:00
2024-09-01T14:41:52.838851+00:00
11
false
```\nint countPairs(vector<int>& nums) {\n const int maxDigits = size(to_string(*ranges::max_element(nums)));\n vector<string> sNums;\n for (const auto v : nums) {\n const auto s = to_string(v);\n sNums.push_back(string(maxDigits - size(s), \'0\') + s);\n }\n\n int ans = 0;\n unordered_map<string, int> dp;\n for (auto& s : sNums) {\n const auto copy = s;\n unordered_set<string> processed;\n const auto updateAns = [&]() {\n if (const auto [_, inserted] = processed.insert(s); inserted) {\n if (const auto it = dp.find(s); it != end(dp)) {\n ans += it->second;\n }\n }\n };\n updateAns();\n for (int x1 = 0; x1 < size(s); ++x1) {\n for (int x2 = 0; x2 < x1; ++x2) {\n swap(s[x1], s[x2]);\n updateAns();\n for (int y1 = 0; y1 < size(s); ++y1) {\n for (int y2 = 0; y2 < y1; ++y2) {\n swap(s[y1], s[y2]);\n updateAns();\n swap(s[y1], s[y2]);\n }\n }\n swap(s[x1], s[x2]);\n }\n }\n ++dp[s];\n }\n return ans;\n}\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
🔥🔥🔥C++ | Step-Wise Approach Explained 🔥🔥🔥 | Counting Pairs with Two Swaps
c-step-wise-approach-explained-counting-0blqa
Approach\n\n### 1. Convert Numbers to Fixed-Length Strings\nTo compare numbers of different lengths, we convert each number into a fixed-length string by prepen
sauravchaudhary717
NORMAL
2024-08-31T18:57:04.628803+00:00
2024-08-31T18:57:04.628840+00:00
13
false
## Approach\n\n### 1. Convert Numbers to Fixed-Length Strings\nTo compare numbers of different lengths, we convert each number into a fixed-length string by prepending zeros. The length of the strings is determined by the number of digits in the largest number in the array.\n\n### 2. Generate All Possible Formations\nFor each number, we generate all possible variations of the number that can be formed by swapping any two digits at most twice. This is done using nested loops to explore all possible digit swaps. These variations are stored in a set to avoid duplicates.\n\n### 3. Count Matching Pairs\nWe maintain a hashmap to store the count of each variation we encounter as we iterate through the array. For each number, we check how many of its variations have already been encountered, and we add this count to our result.\n\n### 4. Complexity\n- The maximum length of the numbers is 7 digits, so the complexity of generating all formations is `7*7*7*7`, which is manageable.\n- The overall time complexity depends on the number of numbers in the input array and the number of digits in the largest number.\n\n## Code\n\n```cpp\nclass Solution {\npublic:\n // Convert a number to a fixed-length string by prepending zeros.\n string generateString(int num, int digit) {\n string s = to_string(num);\n while (s.length() < digit) {\n s = "0" + s;\n }\n return s;\n }\n\n // Generate all possible variations of a number by swapping digits.\n void generateFormations(set<string>& s, int num, int digit) {\n string nums = generateString(num, digit);\n s.insert(nums);\n for (int i = 0; i < nums.length() - 1; i++) {\n for (int j = i + 1; j < nums.length(); j++) {\n if (nums[i] == nums[j]) continue;\n swap(nums[i], nums[j]);\n s.insert(nums);\n for (int k = 0; k < nums.length() - 1; k++) {\n for (int l = k + 1; l < nums.length(); l++) {\n if (nums[k] == nums[l]) continue;\n swap(nums[k], nums[l]);\n s.insert(nums);\n swap(nums[k], nums[l]);\n }\n }\n swap(nums[i], nums[j]);\n }\n }\n }\n\n // Count pairs of numbers that can be made equal by two swaps.\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n int digit = to_string(*max_element(nums.begin(), nums.end())).size();\n unordered_map<string, int> mp;\n int ans = 0;\n\n for (int i = 0; i < nums.size(); i++) {\n unordered_set<string> s;\n generateFormations(s, nums[i], digit);\n for (auto u : s) {\n if (mp[u]) {\n ans += mp[u];\n }\n }\n mp[generateString(nums[i], digit)] += 1;\n }\n return ans;\n }\n};\n
0
0
['C++']
0
count-almost-equal-pairs-ii
Rusty approach using custom Numerals struct and duplicate counting.
rusty-approach-using-custom-numerals-str-j6uh
Intuition\n"Hey, this should be easy, right?" I mean, it\'s just like part 1 but with two swaps instead of one. How hard could it be? Famous last words. Turns o
jkoudys
NORMAL
2024-08-29T14:15:02.460811+00:00
2024-08-29T14:15:02.460851+00:00
11
false
# Intuition\n"Hey, this should be easy, right?" I mean, it\'s just like part 1 but with two swaps instead of one. How hard could it be? Famous last words. Turns out, adding that second swap opens up a world of pain, and what seemed like a minor tweak quickly snowballed into a full-blown headache.\n\n# Approach\nIf I\'m going to have to write so much, I might as well take a Rusty approach and build something that bears a passing resemblance to real code.\n\nI created a Numerals type because, why not? It lets me get the performance of using numbers directly but with the convenience of strings\u2014because sometimes you just need the best of both worlds.\n\nNow, instead of doing something ridiculous like sorting every possible permutation of digits (ugh), I keyed everything on a simple digit count slice. Way quicker, way cleaner. Also, I figured out a neat little trick: counting repeating numbers in order to save time and memory. It\u2019s like LeetCode set me up, but I came prepared with a rusty hammer and nailed it anyway.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\nMaybe? It\'s definitely a lot slower on big sets. I\'m not paying premium and this is chatgpt\'s best guess.\n\n- Space complexity:\n$$O(n)$$\nWe only store a single, linear version of the data. The `i32`s get turned into `[u8; 8]`s and we add a few `[u8; 10s]`s as digit counts we can use to hash the numbers with the same digits together. We\'ll also remove duplicates, so on the balance it\'ll take a little more or a little less than 2x the input vec.\n\nIf you\'re really strapped for memory, you can do the old leetcode trick of changing the function arg to make the input vec mutable. I didn\'t since I think it\'s a cheap trick, but it does save you a little.\n\n# Code\n```rust []\nuse std::collections::HashMap;\n\nconst MAXNUMS: usize = 7;\n\n#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, PartialOrd)]\nstruct Numerals([u8; MAXNUMS]);\nimpl Numerals {\n // A little count of how often each digit comes up, for using as a hash key\n // to match when two nums have the same digits\n fn digit_count(self) -> [u8; 10] {\n let mut count = [0; 10];\n for numeral in self.0.iter() {\n count[*numeral as usize] += 1;\n }\n count\n }\n}\n\nimpl From<i32> for Numerals {\n // Take the digits from the number into our vec\n fn from(n: i32) -> Self {\n let mut n = n;\n let mut v = [0; MAXNUMS];\n for i in 0..MAXNUMS {\n v[MAXNUMS - 1 - i] = (n % 10) as u8;\n n /= 10;\n }\n Self(v)\n }\n}\n\nimpl From<&i32> for Numerals {\n fn from(n: &i32) -> Self {\n Self::from(*n)\n }\n}\n\n// Helper function to check if two strings are almost equal (differ by up to two characters)\nfn can_be_equal_with_two_swaps(s1: Numerals, s2: Numerals) -> bool {\n // If they\'re equal, they\'re also almost equal.\n if s1 == s2 {\n return true;\n }\n\n // Collect the differing u8 between the two numerals\n let dp: Vec<(u8, u8)> =\n s1.0.iter()\n .zip(s2.0.iter())\n .filter_map(|(&c1, &c2)| if c1 == c2 { None } else { Some((c1, c2)) })\n .take(5)\n .collect();\n\n // If there\'s only one diff when the numerals are the same, it\'s almost.\n if dp.len() == 2 {\n return true;\n }\n\n // Can\'t get to matching in more than 2 swaps then\n if dp.len() > 4 {\n return false;\n }\n\n // First pass: Direct swaps that cancel out a pair\n let mut marked: Vec<Option<(u8, u8)>> = dp.iter().map(|p| Some(*p)).collect();\n let mut swapcount = 0;\n for i in 0..marked.len() {\n if marked[i].is_none() {\n continue;\n }\n for j in i + 1..marked.len() {\n // flip and see if the swap cancels\n if let Some((c1, c2)) = marked[j] {\n if Some((c2, c1)) == marked[i] {\n marked[i] = None;\n marked[j] = None;\n swapcount += 1;\n break;\n }\n }\n }\n }\n if swapcount == 2 {\n true\n } else if dp.len() == 4 {\n false\n } else {\n // Graph through the 3 nodes looking for a loop. If it does, we\'ve got a 2-swap\n (dp[0].1 == dp[1].0 && dp[1].1 == dp[2].0 && dp[2].1 == dp[0].0)\n || (dp[0].1 == dp[2].0 && dp[2].1 == dp[1].0 && dp[1].1 == dp[0].0)\n }\n}\n\nimpl Solution {\n pub fn count_pairs(nums: Vec<i32>) -> i32 {\n let mut nums = nums.clone();\n nums.sort_unstable();\n nums.into_iter()\n .fold(Vec::new(), |mut nc: Vec<(i32, usize)>, e| {\n if let Some(last) = nc.pop() {\n if e == last.0 {\n nc.push((e, last.1 + 1));\n } else {\n nc.push(last);\n nc.push((e, 1));\n }\n } else {\n nc.push((e, 1));\n }\n nc\n })\n .iter()\n .map(|(num, count)| (Numerals::from(num), *count))\n .fold(\n HashMap::new(),\n |mut sorted_map: HashMap<[u8; 10], Vec<(Numerals, usize)>>, original| {\n let key = original.0.digit_count();\n sorted_map.entry(key).or_default().push(original);\n sorted_map\n },\n )\n .values()\n // Count up in each group that has the same digits, which can be swapped together\n .fold(0usize, |mut count, group| {\n let len = group.len();\n for i in 0..len {\n // Shaped like itself\n // Count pairs of identical numbers\n count += group[i].1 * (group[i].1 - 1) / 2;\n for j in i + 1..len {\n count += (can_be_equal_with_two_swaps(group[i].0, group[j].0) as usize)\n * group[i].1\n * group[j].1;\n }\n }\n count\n }) as i32\n }\n}\n```
0
0
['Rust']
0
count-almost-equal-pairs-ii
Easy Brute force Solution C++ Code
easy-brute-force-solution-c-code-by-ibra-ico8
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Ibrahim_Hassan
NORMAL
2024-08-29T12:58:17.754580+00:00
2024-08-29T12:58:17.754616+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n Solution() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n }\n\n unordered_set<int> getit(string &s) {\n unordered_set<int> st;\n for (int k = 0; k < s.size(); ++k) {\n for (int l = k + 1; l < s.size(); ++l) {\n string x = s;\n swap(x[k], x[l]);\n st.insert(stoi(x));\n for (int i = 0; i < s.size(); ++i) {\n for (int j = i + 1; j < s.size(); ++j) {\n string a = x;\n swap(a[i], a[j]);\n st.insert(stoi(a));\n }\n }\n }\n }\n if (st.empty())st.insert(stoi(s));\n return st;\n }\n\n int countPairs(vector<int> &nums) {\n unordered_map<int, unordered_set<int>> v;\n string sz = to_string(*max_element(nums.begin(), nums.end()));\n for (int i = 0; i < nums.size(); ++i) {\n string s = to_string(nums[i]);\n while (s.size() < sz.size()) s = \'0\' + s;\n v[nums[i]] = getit(s);\n }\n unordered_map<int, int> fre;\n for (auto &it: nums) fre[it]++;\n int ans = 0;\n for (int i = 0; i < nums.size(); ++i) {\n --fre[nums[i]];\n for (auto &it: v[nums[i]])\n ans += fre[it];\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Super simple java O(N*d^4) solution and explain
super-simple-java-ond4-solution-and-expl-nzq8
Intuition\n Describe your first thoughts on how to solve this problem. \nThe contraints were very tight, so a simple O(N^2) implementation might not work (thoug
vivekgpt107
NORMAL
2024-08-28T14:17:17.804039+00:00
2024-08-28T14:17:17.804070+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe contraints were very tight, so a simple O(N^2) implementation might not work (though it had for this problem). To solve this we need to think of a way to avoid the comparision between each pair of numbers, for this we should notice whether any subproblems are repeating or not, here we figure out that if we precompute find all the two swap variations of all the numbers and count how many times those variations have occured in HashMap datastructure, then we can find the answer by running a single for loop on the given int[] nums, counting the number of times a number has appeared in the hashmap.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nAdd your time complexity here, e.g. $$O(n*d^4)$$\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n int[] pow = new int[]{1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000};\n public int countPairs(int[] nums) {\n Map<Integer, Integer> variations = new HashMap<>();\n int ans = 0;\n for(int i = 0; i < nums.length; i++){\n ans += variations.getOrDefault(nums[i], 0);\n // generate all twoSwaps\n Set<Integer> twoSwaps = new HashSet<>();\n for(int oneSwap: genOneSwap(nums[i]))\n twoSwaps.addAll(genOneSwap(oneSwap));\n for(int twoSwap: twoSwaps)\n variations.put(twoSwap, variations.getOrDefault(twoSwap, 0)+1);\n }\n\n return ans;\n }\n\n public Set<Integer> genOneSwap(int x){\n Set<Integer> oneSwaps = new HashSet<>();\n oneSwaps.add(x);\n int digit = 7;\n for(int i = 0; i < digit; i++){\n for(int j = i+1; j < digit; j++){\n int di = (x/pow[i])%10;\n int dj = (x/pow[j])%10;\n\n // swap\n int varx = x - di*pow[i] + dj*pow[i] - dj*pow[j] + di*pow[j];\n oneSwaps.add(varx);\n }\n }\n return oneSwaps;\n }\n}\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Hash Table
hash-table-by-azizkaz-fhoi
Intuition\n Describe your first thoughts on how to solve this problem. \n1) There exist maximum $21 \cdot 21$ combinations for each number from $nums$ array.\n\
azizkaz
NORMAL
2024-08-28T07:25:38.533720+00:00
2024-08-28T07:28:52.138092+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1) There exist maximum $21 \\cdot 21$ combinations for each number from $nums$ array.\n\n2) It needs to use Hash Table to count almost equal pairs\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHash Table\n\n# Complexity\n- Time complexity: $O(7 \\cdot 21 \\cdot 21 \\cdot n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(n + 7 \\cdot 21 \\cdot 22)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nwhere $n$ is the length of the $nums$ array\n\n# Code\n```rust []\nuse std::collections::{HashMap, HashSet};\n\nimpl Solution {\n pub fn count_pairs(nums: Vec<i32>) -> i32 {\n let n = nums.len(); \n\n let mut h = HashMap::<i32, [i32; 2]>::new(); \n\n for n in nums {\n if h.contains_key(&n) {\n let mut t = h[&n].clone();\n\n t[1] += t[0];\n t[0] += 1; \n\n h.insert(n, t);\n } else {\n h.insert(n, [1, 0]);\n }\n\n let mut s = HashSet::from([n]);\n\n Self::check(n, &mut s, &mut h);\n\n let mut v = Vec::new();\n\n for &m in &s {\n if m != n {\n v.push(m);\n }\n }\n\n for m in v {\n Self::check(m, &mut s, &mut h);\n }\n } \n\n let mut r = 0;\n\n for t in h {\n r += t.1[1];\n } \n\n r\n }\n\n pub fn check(mut n: i32, s: &mut HashSet<i32>, h: &mut HashMap<i32, [i32; 2]>) {\n let mut v = [0; 7];\n\n for i in 0..7 {\n v[6-i] = n % 10;\n n /= 10;\n }\n\n for i in 0..6 {\n for j in i+1..7 {\n if v[i] != v[j] {\n let d = Self::digit(&v, i, j);\n\n if !s.contains(&d) {\n if h.contains_key(&d) {\n let mut t = h[&d];\n\n t[1] += t[0];\n\n h.insert(d, t);\n }\n \n s.insert(d);\n }\n }\n }\n } \n }\n\n pub fn digit(v: &[i32; 7], i: usize, j: usize) -> i32 {\n let mut r = 0;\n\n for k in 0..7 {\n let d = if k == i {v[j]} else if k == j {v[i]} else {v[k]};\n\n r += d * 10_i32.pow(6 - k as u32);\n }\n\n r\n }\n}\n```
0
0
['Hash Table', 'Rust']
0
count-almost-equal-pairs-ii
Brute Force Using Map
brute-force-using-map-by-avatar_027-fg72
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Avatar_027
NORMAL
2024-08-27T20:29:19.230964+00:00
2024-08-27T20:29:19.230995+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#define ll long long\nclass Solution {\npublic:\n unordered_set<string> f(string& s, ll n){\n unordered_set<string> st;\n st.insert(s);\n for(ll i=0; i<n; i++){\n for(ll j=i+1; j<n; j++){\n if(s[i]!=s[j]){\n swap(s[i], s[j]);\n st.insert(s);\n for(ll i1=0; i1<n; i1++){\n for(ll i2=i1+1; i2<n; i2++){\n if(i!=i1 and j!=i2){\n swap(s[i1], s[i2]);\n st.insert(s);\n swap(s[i1], s[i2]);\n }\n }\n }\n swap(s[i], s[j]);\n }\n }\n }\n return st;\n }\n int countPairs(vector<int>& nums) {\n vector<string> v;\n ll n=nums.size();\n ll ans=0;\n for(ll i=0; i<n; i++){\n string str=to_string(nums[i]);\n while(str.length()<7) str=\'0\'+str;\n v.push_back(str);\n }\n unordered_map<string, ll> mp;\n mp[v[0]]++;\n for(ll i=1; i<n; i++){\n unordered_set<string> st=f(v[i], 7);\n for(auto e: st){\n if(mp.count(e)) ans+=mp[e];\n }\n mp[v[i]]++;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Brute Force || Beats 92% || Easy to understand || Maths || C++
brute-force-beats-92-easy-to-understand-skivp
Complexity\n- Time complexity:O(n * 8^4)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(max(nums))\n Add your space complexity here, e.g. O
dubeyad2003
NORMAL
2024-08-27T16:25:15.956231+00:00
2024-08-27T16:25:15.956272+00:00
20
false
# Complexity\n- Time complexity:$$O(n * 8^4)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(max(nums))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int maxi = *max_element(nums.begin(), nums.end());\n vector<int> freq(maxi + 1), vis(maxi + 1, -1);\n int n = nums.size(), ans = 0;\n for(int i=0; i<n; i++){\n int num = nums[i];\n int an = 10000000;\n for(int a=0; a<8; a++){\n int bn = 10000000;\n for(int b=0; b<8; b++){\n // swap the ath digit and bth digit\n int da = num / an;\n int diga = da % 10;\n int db = num / bn;\n int digb = db % 10;\n int new_num = num - diga * an + digb * an - digb * bn + diga * bn;\n int cn = 10000000;\n for(int c=0; c<8; c++){\n int dn = 10000000;\n for(int d=0; d<8; d++){\n // swap the cth digit and dth digit\n int dc = new_num / cn;\n int digc = dc % 10;\n int dd = new_num / dn;\n int digd = dd % 10;\n int nn = new_num - digc * cn + digd * cn - digd * dn + digc * dn;\n if(nn <= maxi && vis[nn] < i){\n vis[nn] = i;\n ans += freq[nn];\n }\n dn /= 10;\n }\n cn /= 10;\n }\n bn /= 10;\n }\n an /= 10;\n }\n freq[nums[i]]++;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
One More Easier Solution | | C++
one-more-easier-solution-c-by-loganblue-uj0s
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
LOGANBLUE
NORMAL
2024-08-27T05:01:44.793685+00:00
2024-08-27T05:01:44.793719+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n unordered_set<string> possiblePatterns(string s, int len) {\n unordered_set<string> poss;\n poss.insert(s);\n \n for(int i = 0; i < len; ++i) {\n for(int j = i + 1; j < len; ++j) {\n swap(s[i], s[j]);\n poss.insert(s);\n for(int a = 0; a < len; ++a) {\n for(int b = a+1; b < len; ++b) {\n if(s[a] != s[b]) {\n swap(s[a], s[b]);\n poss.insert(s);\n swap(s[b], s[a]);\n }\n }\n }\n swap(s[i], s[j]);\n }\n }\n return poss;\n }\npublic:\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n int maxLen = to_string(*max_element(nums.begin(),nums.end())).size();\n auto makeDigit = [&](int num) {\n string s = to_string(num);\n int n = s.size();\n for(int i=0;i<maxLen-n;i++)\n s = "0" + s;\n return s;\n };\n vector<string>numString;\n for(auto&i : nums){\n numString.push_back(makeDigit(i));\n }\n \n unordered_map<string, int> mp;\n int ans = 0;\n for(int i = 0; i < n; ++i) {\n for(const auto& s : possiblePatterns(numString[i], maxLen)) {\n ans += mp[s];\n }\n mp[numString[i]]++;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Brute force beating 93.2% in time
brute-force-beating-932-in-time-by-maxor-ppxn
Not much algorithm found in this question ..\n\nPerhaps the most subtle point is to convert the nums into a set to avoid duplicated calculation?\n\n# Code\npyth
MaxOrgus
NORMAL
2024-08-27T03:26:09.340833+00:00
2024-08-27T03:26:09.340853+00:00
20
false
Not much algorithm found in this question ..\n\nPerhaps the most subtle point is to convert the nums into a set to avoid duplicated calculation?\n\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n possiblepair = {}\n \n res = 0\n nums = [str(n) for n in nums]\n m = max([len(s) for s in nums])\n for i in range(len(nums)):\n if len(nums[i])!=m:\n nums[i] = \'0\'*(m-len(nums[i]))+nums[i]\n @cache\n def swap(s):\n m = len(s)\n res = set([])\n for i in range(m):\n for j in range(i+1,m):\n res.add(s[:i]+s[j]+s[i+1:j]+s[i]+s[j+1:])\n return res\n \n freq = Counter(nums)\n for s in set(nums):\n res += freq[s]*(freq[s]-1) \n change1 = swap(s)\n changes = set([])\n for c in change1:\n change2=swap(c)\n changes.add(c)\n for cc in change2:\n changes.add(cc)\n for c in changes:\n if c in freq and c!=s:\n res += freq[c]*freq[s]\n return res // 2\n \n \n```
0
0
['Python3']
0
count-almost-equal-pairs-ii
Hash Solution, C
hash-solution-c-by-fitran-pmca
Intuition\nTo solve the problem of finding pairs of "almost equal" numbers in the array, we can use a hash table. The idea is to generate all possible numbers t
Fitran
NORMAL
2024-08-26T18:10:40.391073+00:00
2024-08-28T12:03:08.164823+00:00
27
false
# Intuition\nTo solve the problem of finding pairs of "almost equal" numbers in the array, we can use a hash table. The idea is to generate all possible numbers that can be formed by swapping up to two pairs of digits in each number and check if they exist in the hash table. By storing previously encountered numbers in the hash table, we can quickly identify and count valid pairs involving the current number and its variations.\n\n# Approach\n1. **Initialize the Hash Table:** Start by initializing a hash table to store each number from the array along with its occurrence count as it is processed.\n2. **Process Each Number:**\n - Check the Original Number: For each number in the array, first check if it exists in the hash table. If it does, add its count to the result (since this represents a valid "almost equal" pair with itself) and increment the count in the hash table.\n - Generate All Possible 2-Digit Swaps: For each number, generate all possible numbers that can be formed by swapping any two digits. For each swapped number:\n - Check if it exists in the hash table.\n - If it does, ensure it hasn\u2019t been counted already for the current number (using a marking system to track this). If it hasn\u2019t been counted, add its count to the result and mark it to avoid double-counting.\n - Handle Multiple Swaps: Consider additional swaps to handle cases where swapping two different pairs of digits might create different valid pairs.\n3. **Clear the Hash Table:** After processing all numbers, clear the hash table to release memory resources.\n\n# Complexity\nLet $$n$$ be the number of elements in array `nums`. Let $$d$$ be the number of maximum digits.\n- Time complexity: $$O(n \\times d^4)$$\n - Traversing through every elements in array nums and check every possible 2 digit swap: $$O(n\xD7d^4)$$\n - Clearing hash table: $$O(n)$$\n- Space complexity: $$O(n)$$\n - For hash table: $$O(n)$$\n - Other auxiliary variables: $$O(1)$$\n\n# Code 1\n``` C []\nint countPairs(int* nums, int numsSize) {\n int swapped, res = 0, pow10[7] = {1000000, 100000, 10000, 1000, 100, 10, 1};\n short i;\n int8_t s1a, s1b, s2a, s2b, d1a, d1b, d2a, d2b;\n\n struct HashTable{\n int num;\n short count, mark;\n UT_hash_handle hh;\n } *hashTable = NULL, *item;\n\n for(i = 0; i < numsSize; i++){\n swapped = nums[i];\n \n HASH_FIND_INT(hashTable, &swapped, item);\n if(item) res += item->count++;\n else{\n item = (struct HashTable*)malloc(sizeof(struct HashTable));\n\n item->num = swapped;\n item->count = 1;\n item->mark = -1;\n\n HASH_ADD_INT(hashTable, num, item);\n }\n\n for(s1a = 0; s1a < 6; s1a++){\n for(s1b = s1a + 1; s1b < 7; s1b++){\n d1a = swapped / pow10[s1a] % 10;\n d1b = swapped / pow10[s1b] % 10;\n\n if(d1a != d1b){\n swapped -= d1a * pow10[s1a], swapped += d1b * pow10[s1a];\n swapped -= d1b * pow10[s1b], swapped += d1a * pow10[s1b];\n\n HASH_FIND_INT(hashTable, &swapped, item);\n if(item && item->mark != i)\n res += item->count, item->mark = i;\n\n for(s2a = s1a + 1; s2a < 6; s2a++){\n for(s2b = s2a + 1; s2b < 7; s2b++){\n d2a = swapped / pow10[s2a] % 10;\n d2b = swapped / pow10[s2b] % 10;\n\n if(d2a != d2b){\n swapped -= d2a * pow10[s2a], swapped += d2b * pow10[s2a];\n swapped -= d2b * pow10[s2b], swapped += d2a * pow10[s2b];\n\n HASH_FIND_INT(hashTable, &swapped, item);\n if(item && item->mark != i)\n res += item->count, item->mark = i;\n \n swapped -= d2a * pow10[s2b], swapped += d2b * pow10[s2b];\n swapped -= d2b * pow10[s2a], swapped += d2a * pow10[s2a];\n }\n }\n }\n \n swapped -= d1a * pow10[s1b], swapped += d1b * pow10[s1b];\n swapped -= d1b * pow10[s1a], swapped += d1a * pow10[s1a];\n }\n }\n }\n }\n\n HASH_CLEAR(hh, hashTable);\n return res;\n}\n```\n``` C++ []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int swapped, res = 0, pow10[7] = {1000000, 100000, 10000, 1000, 100, 10, 1};\n int8_t s1a, s1b, s2a, s2b, d1a, d1b, d2a, d2b;\n\n unordered_map<int, pair<short, short>> hashTable;\n\n for(short i, n = nums.size(); i < n; i++){\n swapped = nums[i];\n\n res += hashTable[swapped].first++;\n\n for(s1a = 0; s1a < 6; s1a++){\n for(s1b = s1a + 1; s1b < 7; s1b++){\n d1a = swapped / pow10[s1a] % 10;\n d1b = swapped / pow10[s1b] % 10;\n\n if(d1a != d1b){\n swapped += (d1b - d1a) * pow10[s1a] + (d1a - d1b) * pow10[s1b];\n\n if(hashTable.find(swapped) != hashTable.end() && hashTable[swapped].second != i)\n res += hashTable[swapped].first, hashTable[swapped].second = i;\n\n for(s2a = s1a + 1; s2a < 6; s2a++){\n for(s2b = s2a + 1; s2b < 7; s2b++){\n d2a = swapped / pow10[s2a] % 10;\n d2b = swapped / pow10[s2b] % 10;\n \n if(d2a != d2b){\n swapped += (d2b - d2a) * pow10[s2a] + (d2a - d2b) * pow10[s2b];\n\n if(hashTable.find(swapped) != hashTable.end() && hashTable[swapped].second != i)\n res += hashTable[swapped].first, hashTable[swapped].second = i;\n \n swapped += (d2b - d2a) * pow10[s2b] + (d2a - d2b) * pow10[s2a];\n\n }\n }\n }\n \n swapped += (d1b - d1a) * pow10[s1b] + (d1a - d1b) * pow10[s1a];\n }\n }\n }\n }\n\n return res;\n }\n};\n```\n``` Java []\nclass Solution {\n public int countPairs(int[] nums) {\n int swapped, res = 0;\n int[] pow10 = {1000000, 100000, 10000, 1000, 100, 10, 1};\n byte s1a, s1b, s2a, s2b, d1a, d1b, d2a, d2b;\n\n HashMap<Integer, Pair<Short, Short>> hashTable = new HashMap<Integer, Pair<Short, Short>>();\n Pair<Short, Short> entry;\n\n for(short i = 0, n = (short) nums.length; i < n; i++){\n swapped = nums[i];\n\n entry = hashTable.getOrDefault(swapped, new Pair<>((short) 0, (short) 0));\n res += entry.getKey();\n hashTable.put(swapped, new Pair<>((short) (entry.getKey() + 1), (short) entry.getValue()));\n\n for(s1a = 0; s1a < 6; s1a++){\n for(s1b = (byte) (s1a + 1); s1b < 7; s1b++){\n d1a = (byte) (swapped / pow10[s1a] % 10);\n d1b = (byte) (swapped / pow10[s1b] % 10);\n\n if(d1a != d1b){\n swapped += (d1b - d1a) * pow10[s1a] + (d1a - d1b) * pow10[s1b];\n\n entry = hashTable.getOrDefault(swapped, new Pair<>((short) 0, (short) 0));\n if(entry.getKey() > 0 && entry.getValue() != i){\n res += entry.getKey();\n hashTable.put(swapped, new Pair<>((short) entry.getKey(), i));\n }\n\n for(s2a = (byte) (s1a + 1); s2a < 6; s2a++){\n for(s2b = (byte) (s2a + 1); s2b < 7; s2b++){\n d2a = (byte) (swapped / pow10[s2a] % 10);\n d2b = (byte) (swapped / pow10[s2b] % 10);\n\n if(d2a != d2b){\n swapped += (d2b - d2a) * pow10[s2a] + (d2a - d2b) * pow10[s2b];\n\n entry = hashTable.getOrDefault(swapped, new Pair<>((short) 0, (short) 0));\n if(entry.getKey() > 0 && entry.getValue() != i){\n res += entry.getKey();\n hashTable.put(swapped, new Pair<>((short) entry.getKey(), i));\n }\n \n swapped += (d2b - d2a) * pow10[s2b] + (d2a - d2b) * pow10[s2a];\n }\n }\n }\n\n swapped += (d1b - d1a) * pow10[s1b] + (d1a - d1b) * pow10[s1a];\n }\n }\n }\n }\n\n return res;\n }\n}\n```\n``` Python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n pow10 = (1000000, 100000, 10000, 1000, 100, 10, 1)\n\n hashTable = {}\n\n res, n = 0, len(nums)\n for i in range(n):\n swapped = nums[i]\n\n entry = hashTable.get(swapped, (0, 0))\n res += entry[0]\n hashTable[swapped] = (entry[0] + 1, entry[1])\n\n for s1a in range(6):\n for s1b in range(s1a + 1, 7):\n d1a = int(swapped / pow10[s1a] % 10)\n d1b = int(swapped / pow10[s1b] % 10)\n\n if d1a != d1b:\n swapped += (d1b - d1a) * pow10[s1a] + (d1a - d1b) * pow10[s1b]\n\n entry = hashTable.get(swapped, (0, 0))\n if entry[0] > 0 and entry[1] != i:\n res += entry[0]\n hashTable[swapped] = (entry[0], i)\n\n for s2a in range(s1a + 1, 6):\n for s2b in range(s2a + 1, 7):\n d2a = int(swapped / pow10[s2a] % 10)\n d2b = int(swapped / pow10[s2b] % 10)\n\n if d2a != d2b:\n swapped += (d2b - d2a) * pow10[s2a] + (d2a - d2b) * pow10[s2b]\n\n entry = hashTable.get(swapped, (0, 0))\n if entry[0] > 0 and entry[1] != i:\n res += entry[0]\n hashTable[swapped] = (entry[0], i)\n\n swapped += (d2b - d2a) * pow10[s2b] + (d2a - d2b) * pow10[s2a]\n\n swapped += (d1b - d1a) * pow10[s1b] + (d1a - d1b) * pow10[s1a]\n\n return res\n```\n# Code 2 (String Conversion)\nNote: This code is slower than the previous code.\n``` C []\nint countPairs(int* nums, int numsSize) {\n char swap, *strForm = (char*)malloc(8);\n short i, j, s1a, s1b, s2a, s2b;\n int dig, res = 0;\n\n struct HashTable{\n char *num;\n short count, mark;\n UT_hash_handle hh;\n } *hashTable = NULL, *item, *tmp;\n\n for(i = 0, strForm[7] = \'\\0\'; i < numsSize; i++){\n for(dig = 1000000, j = 0; dig > 0; dig /= 10, j++)\n strForm[j] = (nums[i] / dig % 10) + \'0\';\n \n HASH_FIND_STR(hashTable, strForm, item);\n if(item) res += item->count++;\n else{\n item = (struct HashTable*)malloc(sizeof(struct HashTable));\n item->num = (char*)malloc(8);\n\n for(int8_t i = 0; i < 8; i++)\n item->num[i] = strForm[i];\n item->count = 1;\n item->mark = -1;\n\n HASH_ADD_STR(hashTable, num, item);\n }\n\n for(s1a = 0; s1a < 6; s1a++){\n for(s1b = s1a + 1; s1b < 7; s1b++){\n if(strForm[s1a] != strForm[s1b]){\n swap = strForm[s1b], strForm[s1b] = strForm[s1a], strForm[s1a] = swap;\n\n HASH_FIND_STR(hashTable, strForm, item);\n if(item && item->mark != i)\n res += item->count, item->mark = i;\n\n for(s2a = s1a + 1; s2a < 6; s2a++){\n for(s2b = s2a + 1; s2b < 7; s2b++){\n if(strForm[s2a] != strForm[s2b]){\n swap = strForm[s2b], strForm[s2b] = strForm[s2a], strForm[s2a] = swap;\n HASH_FIND_STR(hashTable, strForm, item);\n if(item && item->mark != i)\n res += item->count, item->mark = i;\n swap = strForm[s2b], strForm[s2b] = strForm[s2a], strForm[s2a] = swap;\n }\n }\n }\n \n swap = strForm[s1b], strForm[s1b] = strForm[s1a], strForm[s1a] = swap;\n }\n }\n }\n }\n\n free(strForm);\n HASH_ITER(hh, hashTable, item, tmp){\n HASH_DEL(hashTable, item);\n free(item->num);\n free(item);\n }\n return res;\n}\n```\n``` Python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n hashTable = {}\n\n res, n = 0, len(nums)\n for i in range(n):\n swapped = str(nums[i])\n swapped = \'0\' * (7 - len(swapped)) + swapped\n\n entry = hashTable.get(swapped, (0, 0))\n res += entry[0]\n hashTable[swapped] = (entry[0] + 1, entry[1])\n\n for s1a in range(6):\n for s1b in range(s1a + 1, 7):\n if swapped[s1a] != swapped[s1b]:\n swapped = swapped[:s1a] + swapped[s1b] + swapped[s1a + 1:s1b] + swapped[s1a] + swapped[s1b + 1:]\n\n entry = hashTable.get(swapped, (0, 0))\n if entry[0] > 0 and entry[1] != i:\n res += entry[0]\n hashTable[swapped] = (entry[0], i)\n\n for s2a in range(s1a + 1, 6):\n for s2b in range(s2a + 1, 7):\n if swapped[s2a] != swapped[s2b]:\n swapped = swapped[:s2a] + swapped[s2b] + swapped[s2a + 1:s2b] + swapped[s2a] + swapped[s2b + 1:]\n\n entry = hashTable.get(swapped, (0, 0))\n if entry[0] > 0 and entry[1] != i:\n res += entry[0]\n hashTable[swapped] = (entry[0], i)\n\n swapped = swapped[:s2a] + swapped[s2b] + swapped[s2a + 1:s2b] + swapped[s2a] + swapped[s2b + 1:]\n\n swapped = swapped[:s1a] + swapped[s1b] + swapped[s1a + 1:s1b] + swapped[s1a] + swapped[s1b + 1:]\n\n return res\n```
0
0
['Hash Table', 'String', 'C', 'Hash Function', 'C++', 'Java', 'Python3']
0
count-almost-equal-pairs-ii
Easier to understand Binary search & unordered map use
easier-to-understand-binary-search-unord-j1zi
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
kritimalik9
NORMAL
2024-08-26T18:04:12.826810+00:00
2024-08-26T18:04:12.826875+00:00
14
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n\n std::sort(nums.begin(), nums.end());\n std::unordered_map<int, vector<int>> idx_map;\n for(int n=0; n<nums.size(); n++)\n {\n auto nw = to_string(nums[n]);\n if(!idx_map.count(nums[n]))\n {\n auto [itr, _] = idx_map.emplace(nums[n],std::vector<int>());\n itr->second.push_back(n);\n }\n else\n {\n auto last_idx = idx_map[nums[n]].size() - 1;\n if(idx_map[nums[n]][last_idx] != n)\n {\n idx_map[nums[n]].push_back(n);\n }\n }\n for(int i=0; i<nw.length()-1; i++)\n {\n for(int j=i+1; j<nw.length(); j++)\n {\n if(nw[i] != nw[j])\n {\n string x(nw);\n x[i] = nw[j];\n x[j] = nw[i];\n auto nn = stoi(x);\n if(!idx_map.count(nn))\n {\n auto [itr, _] = idx_map.emplace(nn,std::vector<int>());\n itr->second.push_back(n);\n }\n else\n {\n auto last_idx = idx_map[nn].size() - 1;\n if(idx_map[nn][last_idx] != n)\n {\n idx_map[nn].push_back(n);\n }\n }\n for(int p=0; p<x.length()-1; p++)\n {\n for(int q=i+1; q<x.length(); q++)\n {\n if(x[p] != x[q])\n {\n string y(x);\n y[p] = x[q];\n y[q] = x[p];\n auto yy = stoi(y);\n if(idx_map.find(yy) != idx_map.end())\n {\n auto last_idx = idx_map[yy].size() - 1;\n if(idx_map[yy][last_idx] != n)\n {\n idx_map[yy].push_back(n);\n }\n }\n else\n {\n auto [itr, _] = idx_map.emplace(yy,std::vector<int>());\n itr->second.push_back(n);\n }\n }\n }\n }\n }\n }\n }\n }\n // for(const auto& [val, idcs]: idx_map)\n // {\n // std::cout << val << "->";\n // for(const auto elm: idcs)\n // {\n // std::cout << elm << "|";\n // }\n // std::cout << "::: ";\n // }\n // std::cout << std::endl;\n int count = 0;\n for(int i=0; i<nums.size(); i++)\n {\n const auto& idcs = idx_map.find(nums[i])->second;\n int l=0;\n int r=idcs.size()-1;\n int pos = r+1;\n int find = i+1;\n while(l <= r)\n {\n int m = (l+r)/2;\n if(idcs[m] >= find)\n {\n pos = m;\n r = m-1;\n }\n else\n {\n l = m+1;\n }\n }\n auto cnt = (idcs.size() - pos);\n count = count + cnt;\n\n }\n return count;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Combination of pair Indexes.
combination-of-pair-indexes-by-wangtan83-hie0
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
wangtan83
NORMAL
2024-08-26T17:12:15.985789+00:00
2024-08-26T17:13:26.466008+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n nums.sort( reverse = True)\n\n def generate_almost_equals( intNum, k = 2):\n setEquals = {intNum}\n strNum = str( intNum)\n pairIndexes = list(itertools.combinations( range(len(strNum)), 2))\n\n for numPairs in range( 1, k+1):\n for indexPair in itertools.combinations( pairIndexes, numPairs): \n s = strNum\n for i, j in indexPair:\n s = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]\n setEquals.add( int( s, 10))\n return setEquals\n \n prevSeenNumbers = collections.Counter()\n totalAlmostEquals = 0\n\n for num in nums:\n totalAlmostEquals += prevSeenNumbers[num]\n prevSeenNumbers += collections.Counter( generate_almost_equals( num))\n \n return totalAlmostEquals\n```
0
0
['Python3']
0
count-almost-equal-pairs-ii
Simple Approach Explained!!✅💯🔥
simple-approach-explained-by-manibhushan-3l6k
\n# Complexity\n- Time complexity: O(n * maxSize^4)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n * maxSize^2)\n Add your space complex
Manibhushan20
NORMAL
2024-08-26T15:04:12.178176+00:00
2024-08-26T15:04:12.178226+00:00
19
false
\n# Complexity\n- Time complexity: O(n * maxSize^4)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * maxSize^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n // Variable to store the maximum number of digits among all numbers in nums\n int maxSize = 0;\n\n // Function to convert a number to a string of length maxSize by padding\n // with zeros\n string makeDigit(int num) {\n string s = to_string(num);\n int n = s.size();\n while (n < maxSize) { // While the length is less than maxSize\n s = "0" + s; // Pad with leading zeros\n n++;\n }\n return s;\n }\n\n // Function to generate all unique strings by swapping any two digits any\n // number of times\n unordered_set<string> makeAllSwaps(int num) {\n string s = makeDigit(num);\n unordered_set<string> res;\n res.insert(s);\n\n // Loop to generate all permutations by swapping\n for (int i = 0; i < maxSize; i++) {\n for (int j = i + 1; j < maxSize; j++) {\n swap(s[i], s[j]); // Swap two digits\n res.insert(s); // Insert the new permutation\n\n // Further swap other digits in the new permutation to generate\n // more unique permutations\n for (int l = 0; l < maxSize; l++) {\n for (int k = l + 1; k < maxSize; k++) {\n if (s[l] != s[k])\n swap(s[l], s[k]);\n res.insert(s);\n swap(s[l], s[k]);\n }\n }\n swap(s[i], s[j]);\n }\n }\n\n return res;\n }\n\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n maxSize = to_string(*max_element(nums.begin(), nums.end())).size();\n int ans = 0;\n unordered_map<string, int> mp;\n\n for (int i = 0; i < n; i++) {\n // Generate all unique permutations for the current number\n for (auto& s : makeAllSwaps(nums[i])) {\n // If this permutation is already in the map, add its count to\n // ans\n if (mp.count(s)) {\n ans += mp[s];\n }\n }\n // Store the zero-padded representation of the current number in the\n // map\n mp[makeDigit(nums[i])]++;\n }\n\n return ans;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Easy Java Solution
easy-java-solution-by-danish_jamil-gj30
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Danish_Jamil
NORMAL
2024-08-26T07:27:34.460569+00:00
2024-08-26T07:27:34.460587+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int n = nums.length;\n int result = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n result += almostEqual(nums[i], nums[j]) ? 1 : 0;\n }\n }\n return result;\n }\n\n private boolean almostEqual(int a, int b) {\n int found = 0;\n // first 4 different digits for a and b\n int[] ad = new int[4];\n int[] bd = new int[4];\n while (a > 0 || b > 0) {\n if (a%10 != b%10) {\n ad[found] = a%10;\n bd[found] = b%10;\n found++;\n }\n a /= 10;\n b /= 10;\n if (found == 4) {\n break;\n } \n }\n\n if (found <= 1) {\n return found == 0;\n }\n if (found == 2 || found == 3) {\n Arrays.sort(ad);\n Arrays.sort(bd);\n return a == b && Arrays.equals(ad, bd);\n }\n // found == 4\n // need to get a matching pair first with the same indices,\n // then all digits should match in any order\n for (int i = 0; i < 3; i++) {\n for (int j = i+1; j < 4; j++) {\n if (ad[i] == bd[j] && ad[j] == bd[i]) {\n Arrays.sort(ad);\n Arrays.sort(bd);\n // a == b -> check if the rest digits are equal, found 5+ case\n return a == b && Arrays.equals(ad, bd);\n }\n }\n }\n return false;\n }\n}\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
CPP BEST SOLUTION
cpp-best-solution-by-shreyanshjain999-2046
C++ SOLUTION\n\nclass Solution {\npublic:\n string str(int digits,int num){\n int a=log10(num)+1;\n string s=to_string(num);\n for(int i
Shreyanshjain999
NORMAL
2024-08-26T06:55:08.488437+00:00
2024-08-26T06:55:08.488470+00:00
18
false
**C++ SOLUTION**\n\nclass Solution {\npublic:\n string str(int digits,int num){\n int a=log10(num)+1;\n string s=to_string(num);\n for(int i=0;i<digits-a;i++){\n s="0"+s;\n }\n return s;\n }\n unordered_set<string> cases(int digits,int num){\n string s=str(digits,num);\n int n=digits;\n unordered_set<string>pos;\n pos.insert(s);\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n swap(s[i],s[j]);\n pos.insert(s);\n for(int p=0;p<n;p++){\n for(int q=p+1;q<n;q++){\n swap(s[p],s[q]);\n pos.insert(s);\n swap(s[p],s[q]);\n }\n }\n swap(s[i],s[j]);\n }\n }\n return pos;\n }\n int countPairs(vector<int>& nums) {\n int n=nums.size();\n int digits=to_string(*max_element(nums.begin(),nums.end())).size();\n int cnt=0;\n unordered_map<string,int>mpp;\n for(int i=0;i<n;i++){\n for(const auto& s:cases(digits,nums[i])){\n cnt+=mpp[s];\n }\n mpp[str(digits,nums[i])]++;\n }\n return cnt; \n }\n};
0
0
['Greedy', 'C']
0
count-almost-equal-pairs-ii
c++() brute force
c-brute-force-by-zx007pi-w9ve
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
zx007pi
NORMAL
2024-08-26T06:45:22.337378+00:00
2024-08-27T16:44:29.704275+00:00
17
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n vector<vector<int>> t(n, vector<int>(8,0));\n\n for(int i = 0; i != n; i++){\n int x = nums[i], id = -1;\n while(x){\n t[i][++id] = x%10;\n x /= 10;\n }\n }\n\n int ans = 0;\n int na[8], nb[8];\n\n for(int i = 0; i != n-1; i++){\n for(int j = i+1; j != n; j++){\n\n int size = 0; \n for(int k = 0; k != t[i].size(); k++)\n if(t[i][k] != t[j][k]) {\n if(size == 4) goto mark;\n na[size] = t[i][k], nb[size] = t[j][k];\n size++; \n }\n\n if( size == 0 ||\n ( size == 2 && na[0] == nb[1] && nb[0] == na[1] ) ||\n ( size == 3 && ( (na[0] == nb[1] && na[1] == nb[2] && na[2] == nb[0]) ||\n (na[0] == nb[2] && na[1] == nb[0] && na[2] == nb[1]))) || \n ( size == 4 && ( (na[0] == nb[1] && nb[0] == na[1] && na[2] == nb[3] && nb[2] == na[3]) ||\n (na[0] == nb[2] && nb[0] == na[2] && na[1] == nb[3] && nb[1] == na[3]) ||\n (na[0] == nb[3] && nb[0] == na[3] && na[1] == nb[2] && nb[1] == na[2]) ))) ans++;\n mark:\n } \n } \n return ans; \n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
CHECK MY SOLUTION 👇👇
check-my-solution-by-lokeshkumar_2106-adpo
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
lokeshkumar_2106
NORMAL
2024-08-26T05:06:00.905968+00:00
2024-08-26T05:06:00.905996+00:00
22
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nfrom collections import defaultdict\n\nclass Solution:\n def makeDigit(self, num, digits):\n s = str(num)\n return s.zfill(digits)\n\n def makeSwapChanges(self, num, digits):\n s = self.makeDigit(num, digits)\n poss = set()\n poss.add(s)\n\n for i in range(digits):\n for j in range(i + 1, digits):\n # Convert string to a list for swapping\n s_list = list(s)\n # Perform the first swap\n s_list[i], s_list[j] = s_list[j], s_list[i]\n swapped_s = \'\'.join(s_list)\n poss.add(swapped_s)\n\n for i1 in range(digits):\n for j1 in range(i1 + 1, digits):\n if s_list[i1] != s_list[j1]:\n s_list[i1], s_list[j1] = s_list[j1], s_list[i1]\n poss.add(\'\'.join(s_list))\n # Revert the second swap\n s_list[j1], s_list[i1] = s_list[i1], s_list[j1]\n\n # Revert the first swap\n s_list[i], s_list[j] = s_list[j], s_list[i]\n s = \'\'.join(s_list)\n\n return poss\n\n def countPairs(self, nums):\n n = len(nums)\n digits = len(str(max(nums)))\n mp = defaultdict(int)\n ans = 0\n\n for num in nums:\n for s in self.makeSwapChanges(num, digits):\n if s in mp:\n ans += mp[s]\n mp[self.makeDigit(num, digits)] += 1\n\n return ans\n\n```
0
0
['Python3']
0
count-almost-equal-pairs-ii
[C++] Brutal Force
c-brutal-force-by-hesicheng20-zupl
Intuition\nThe key insight is to focus on the differences in their digit arrays and determine if these differences can be reconciled with the allowed swaps.\n\n
hesicheng20
NORMAL
2024-08-26T05:02:12.364170+00:00
2024-08-26T05:02:12.364206+00:00
25
false
# Intuition\nThe key insight is to focus on the differences in their digit arrays and determine if these differences can be reconciled with the allowed swaps.\n\n# Approach\n- **Preprocess Digits**: Convert each number in the array into an array of its digits for easier comparison.\n- **Check Almost Equal**: Implement a function to check if two digit arrays are almost equal by analyzing the number and positions of differing digits, allowing for at most two swaps to reconcile the differences.\n\n# Complexity\n- Time complexity: $O(n^2)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(n)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nbool almost_equal(const array<int, 8> &a, const array<int, 8> &b) {\n array<pair<int, int>, 8> differentPairs\n int diffCount = 0;\n\n for (int i = 0; i < 8; i++) {\n if (a[i] != b[i]) {\n if (diffCount >= 4) {\n return false;\n }\n differentPairs[diffCount++] = {a[i], b[i]};\n }\n }\n\n if (diffCount == 1) {\n return false;\n }\n if (diffCount == 2) {\n return (differentPairs[0].first == differentPairs[1].second &&\n differentPairs[0].second == differentPairs[1].first);\n }\n if (diffCount == 3) {\n return (differentPairs[1].first == differentPairs[0].second &&\n differentPairs[2].first == differentPairs[1].second &&\n differentPairs[0].first == differentPairs[2].second) ||\n (differentPairs[2].first == differentPairs[0].second &&\n differentPairs[0].first == differentPairs[1].second &&\n differentPairs[1].first == differentPairs[2].second);\n }\n if (diffCount == 4) {\n return ((differentPairs[0].first == differentPairs[1].second &&\n differentPairs[0].second == differentPairs[1].first) &&\n (differentPairs[2].first == differentPairs[3].second &&\n differentPairs[2].second == differentPairs[3].first)) ||\n ((differentPairs[0].first == differentPairs[2].second &&\n differentPairs[0].second == differentPairs[2].first) &&\n (differentPairs[1].first == differentPairs[3].second &&\n differentPairs[1].second == differentPairs[3].first)) ||\n ((differentPairs[0].first == differentPairs[3].second &&\n differentPairs[0].second == differentPairs[3].first) &&\n (differentPairs[1].first == differentPairs[2].second &&\n differentPairs[1].second == differentPairs[2].first));\n }\n\n return false;\n}\n\nclass Solution {\npublic:\n int countPairs(vector<int> &nums) {\n const int n = nums.size();\n vector<array<int, 8> > numsArray(n);\n\n // Precompute array representation of nums\n for (int i = 0; i < n; i++) {\n int num = nums[i];\n for (int j = 0; j < 8; j++) {\n numsArray[i][7 - j] = num % 10;\n num /= 10;\n }\n }\n\n int ans = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (nums[i] == nums[j] || almost_equal(numsArray[i], numsArray[j])) {\n ans++;\n }\n }\n }\n return ans;\n }\n};\n\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Python Solution
python-solution-by-krishna5972-mus8
Intuition\n Describe your first thoughts on how to solve this problem. \nTry to generate possible swaps a digit can lead to add up how many pairs are posible wi
krishna5972
NORMAL
2024-08-26T04:32:29.828110+00:00
2024-08-26T04:32:29.828140+00:00
41
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to generate possible swaps a digit can lead to add up how many pairs are posible with the combination if the generated digit is available\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N * D ^ 4)$$\n\n\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n \n n = len(nums)\n available_set= []\n\n visited = defaultdict(lambda:0)\n\n for ele in nums:\n ele = str(ele)\n if len(ele) < 7:\n ele = \'0\' * (7 - len(ele)) + ele\n available_set.append(ele)\n \n count = 0\n for ele in available_set:\n generated_set = set()\n count += visited[ele]\n generated_set.add(ele)\n ele = list(ele)\n for i in range(7):\n for ii in range(i+1,7):\n ele[i],ele[ii] = ele[ii],ele[i]\n digit = "".join(ele)\n if digit not in generated_set:\n generated_set.add(digit)\n count += visited[digit]\n for iii in range(7):\n for iv in range(iii+1,7):\n ele[iii],ele[iv] = ele[iv],ele[iii]\n digit = "".join(ele)\n if digit not in generated_set:\n count += visited[digit]\n generated_set.add(digit)\n ele[iii],ele[iv] = ele[iv],ele[iii]\n ele[i],ele[ii] = ele[ii],ele[i]\n digit = "".join(ele)\n visited[digit] += 1\n \n return count\n \n\n\n```
0
0
['Python3']
1
count-almost-equal-pairs-ii
Beats 100% JAVA
beats-100-java-by-murariambofficial-dwbo
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
murariambofficial
NORMAL
2024-08-26T00:21:00.158829+00:00
2024-08-26T00:21:00.158859+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int n = nums.length;\n String[] strs = new String[n];\n\t\t\n\t\tint result = 0;\n Map<String, List<Integer>> map = new HashMap();\n for (int i = 0; i < n; i++) {\n \tint now = nums[i];\n \tString str = now + "";\n \twhile (str.length() < 7)\n \t\tstr = "0" + str;\n \tstrs[i] = str;\n \tchar[] chars = str.toCharArray();\n \tArrays.sort(chars);\n \tString key = new String(chars);\n \tif (!map.containsKey(key))\n \t\tmap.put(key, new ArrayList());\n \tmap.get(key).add(i);\n }\n for (List<Integer> list : map.values()) {\n\t for (int i = 1; i < list.size(); i++) {\n\t \tfor (int j = 0; j < i; j++) {\n\t \t\tif (check(strs[list.get(i)], strs[list.get(j)]))\n\t \t\t\tresult++;\n\t \t}\n\t }\n }\n return result;\n }\n\t\n\tprivate static boolean check(String a, String b) {\n\t\tList<Integer> list = new ArrayList();\n\t\tfor (int i = 0; i < a.length(); i++) {\n\t\t\tif (a.charAt(i) != b.charAt(i))\n\t\t\t\tlist.add(i);\n\t\t}\n\t\tif (list.size() == 1 || list.size() > 4)\n\t\t\treturn false;\n\t\tif (list.size() < 4)\n\t\t\treturn true;\n\t\tif (check(a, b, list, 0, 1))\n\t\t\treturn true;\n\t\tif (check(a, b, list, 0, 2))\n\t\t\treturn true;\n\t\treturn (check(a, b, list, 0, 3));\n }\n\t\n\tprivate static boolean check(String a, String b, List<Integer> list, int x, int y) {\n\t\treturn a.charAt(list.get(x)) == b.charAt(list.get(y)) && a.charAt(list.get(y)) == b.charAt(list.get(x));\n\t}\n}\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Java Brute Force, using map to group all the ones with same digits
java-brute-force-using-map-to-group-all-72exm
Intuition\n Describe your first thoughts on how to solve this problem. \nSince all the numbers are less than 10^7, so make all the number string with length = 7
realstar
NORMAL
2024-08-26T00:06:09.908738+00:00
2024-08-26T00:06:09.908763+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince all the numbers are less than 10^7, so make all the number string with length = 7, attach 0 in front to make them same length.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing a hashmap, with key = sorted string, so if two string with same chars will have same key. Only compare the ones with same key.\nWhen do comparision, check the indexes with different chars. If their are more than 4 diffs, then it is impossible to make it. If the diff = 2 or 3, we can make it in 1 or 2 swithes. (In fact, there is not possible to have 1 diff only if 2 strings with same chars.) If there are 4 diffs, then make sure it can switch 0,1 or 0,2 or 0,3. Since 0123 and 1230 can\'t make it 2 switches.\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int n = nums.length;\n String[] strs = new String[n];\n\t\t\n\t\tint result = 0;\n Map<String, List<Integer>> map = new HashMap();\n for (int i = 0; i < n; i++) {\n \tint now = nums[i];\n \tString str = now + "";\n \twhile (str.length() < 7)\n \t\tstr = "0" + str;\n \tstrs[i] = str;\n \tchar[] chars = str.toCharArray();\n \tArrays.sort(chars);\n \tString key = new String(chars);\n \tif (!map.containsKey(key))\n \t\tmap.put(key, new ArrayList());\n \tmap.get(key).add(i);\n }\n for (List<Integer> list : map.values()) {\n\t for (int i = 1; i < list.size(); i++) {\n\t \tfor (int j = 0; j < i; j++) {\n\t \t\tif (check(strs[list.get(i)], strs[list.get(j)]))\n\t \t\t\tresult++;\n\t \t}\n\t }\n }\n return result;\n }\n\t\n\tprivate static boolean check(String a, String b) {\n\t\tList<Integer> list = new ArrayList();\n\t\tfor (int i = 0; i < a.length(); i++) {\n\t\t\tif (a.charAt(i) != b.charAt(i))\n\t\t\t\tlist.add(i);\n\t\t}\n\t\tif (list.size() == 1 || list.size() > 4)\n\t\t\treturn false;\n\t\tif (list.size() < 4)\n\t\t\treturn true;\n\t\tif (check(a, b, list, 0, 1))\n\t\t\treturn true;\n\t\tif (check(a, b, list, 0, 2))\n\t\t\treturn true;\n\t\treturn (check(a, b, list, 0, 3));\n }\n\t\n\tprivate static boolean check(String a, String b, List<Integer> list, int x, int y) {\n\t\treturn a.charAt(list.get(x)) == b.charAt(list.get(y)) && a.charAt(list.get(y)) == b.charAt(list.get(x));\n\t}\n}\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Easy Video Solution (Critical Thinking )🔥 || How to 🤔 in Interview || Simulation || String || JAVA
easy-video-solution-critical-thinking-ho-yzcz
Intuition\n# If you like the solution Please Upvote and subscribe to my youtube channel\n\n\n\n\n# EASY VIDEO EXPLANATION \n\n\nhttps://youtu.be/weYmUnmqwZ4\n\n
mmohit073
NORMAL
2024-08-25T20:16:31.293374+00:00
2024-08-25T20:16:31.293400+00:00
10
false
# Intuition\n# **If you like the solution Please Upvote and subscribe to my youtube channel**\n\n\n\n\n# EASY VIDEO EXPLANATION \n\n\nhttps://youtu.be/weYmUnmqwZ4\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\n/*\n\nscenarios :: Possible no of differ digits::\n\n\ncase 1.) if 0 digits differ then already equal\n\n\n\ncase 2.) if 1 digits differ then can\'t made equal by given operation\n exp :: 123 & 124\n\n\n\ncase 3.) if 2 digits differ then we can made 1 swap to make equal\n exp :: (2310,2130) => arrays => \n ar1 : [0,1,3,2] \n ar2 : [0,3,1,2]\n\n differ ind = [1,2] \n \n 1->[2]\n 2->[1]\n\n 0132 -> (1,2) -> 0312\n \n\n\n (ar1[1]==ar2[2] && ar1[2]==ar2[1])\n\n\n\ncase 4.) if 3 digits differ then we can made 2 swap to make equal\n exp :: (2310,0213) => arrays =>\n ar1 : [0,1,3,2] \n ar2 : [3,1,2,0]\n\n differ ind : [0,2,3]\n\n 0 -> [2,3]\n 2 -> [0,3]\n 3 -> [0,2]\n\n 0132 -> (0,2) -> 3102 -> (2,3) -> 3120\n 0132 -> (0,3) -> 2130 -> (3,2) -> 2103\n\n\n\n (ar1[0]==ar2[3] && ar1[3]==ar2[2] && ar1[2]==ar2[0])\n (ar1[0]==ar2[2] && ar1[2]==ar2[3] && ar1[3]==ar2[0])\n\n\n\ncase 5.) if 4 digits differ then we can made 2 swap to make equal\n exp :: (1023,2310) => arrays =>\n ar1 : [3,2,0,1]\n ar2 : [0,1,3,2]\n\n differ ind : [0,1,2,3]\n\n 0 -> [1,2,3]\n 1 -> [0,2,3]\n 2 -> [0,1,3]\n 3 -> [0,1,2]\n\n 1023 -> (0,1) -> 0123 -> (2,3) -> 0132\n 1023 -> (0,2) -> 2013 -> (1,3) -> 2103\n 1023 -> (0,3) -> 3021 -> (1,2) -> 3201\n\n\n (ar1[0]==ar2[1] && ar1[1]==ar2[0] && ar1[2]==ar2[3] && ar1[3]==ar2[2])\n (ar1[0]==ar2[2] && ar1[2]==ar2[0] && ar1[1]==ar2[3] && ar1[3]==ar2[1])\n (ar1[0]==ar2[3] && ar1[3]==ar2[0] && ar1[2]==ar2[1] && ar1[1]==ar2[2]) \n\n\n\ncase 6.) if more the 4 digits differ we can\'t do in 2 swaps\n\n*/\n\nclass Solution {\n\n private int[] convertNumtoArr(int num){\n int[] tmp = new int[8];\n int i=0;\n while(num>0){\n tmp[i]=num%10;\n num /=10;\n i++;\n }\n\n return tmp;\n }\n\n private boolean isEqual(int x,int y){\n int[] xAr = convertNumtoArr(x);\n int[] yAr = convertNumtoArr(y);\n\n int diffDigitCnt=0;\n int[] diffDigitInd=new int[4];\n for(int i=0;i<8;i++){\n if(xAr[i]!=yAr[i]){\n if(diffDigitCnt==4){\n return false;\n }\n diffDigitInd[diffDigitCnt]=i;\n diffDigitCnt++;\n }\n }\n\n if(diffDigitCnt==0){\n return true;\n }\n\n if(diffDigitCnt==2){\n int a = diffDigitInd[0];\n int b = diffDigitInd[1];\n\n return (xAr[a]==yAr[b] && xAr[b]==yAr[a]);\n }\n\n if(diffDigitCnt==3){\n int a = diffDigitInd[0];\n int b = diffDigitInd[1];\n int c = diffDigitInd[2];\n\n return (xAr[a]==yAr[b] && xAr[b]==yAr[c] && xAr[c]==yAr[a])\n ||(xAr[a]==yAr[c] && xAr[c]==yAr[b] && xAr[b]==yAr[a]);\n }\n\n if(diffDigitCnt==4){\n int a = diffDigitInd[0];\n int b = diffDigitInd[1];\n int c = diffDigitInd[2];\n int d = diffDigitInd[3];\n\n return (xAr[a]==yAr[b] && xAr[b]==yAr[a] && xAr[c]==yAr[d] && xAr[d]==yAr[c])||\n (xAr[a]==yAr[c] && xAr[c]==yAr[a] && xAr[b]==yAr[d] && xAr[d]==yAr[b])|| \n (xAr[a]==yAr[d] && xAr[d]==yAr[a] && xAr[c]==yAr[b] && xAr[b]==yAr[c]);\n }\n\n return false;\n }\n\n\n public int countPairs(int[] nums) {\n int len = nums.length;\n int res = 0;\n for(int i=0;i<nums.length-1;i++){\n for(int j=i+1;j<nums.length;j++){\n if(isEqual(nums[i],nums[j])){\n res++;\n }\n }\n }\n\n return res;\n }\n}\n```
0
0
['Math', 'String', 'Java']
0
count-almost-equal-pairs-ii
[Java] Enumerating all the possible neighbors
java-enumerating-all-the-possible-neighb-iqyt
Intuition\nAfter trying so many optimizations for the brute force approach, which tries to enumerate all the results after swapping nums[i] and nums[j], where i
deepanshu
NORMAL
2024-08-25T17:14:45.030422+00:00
2024-08-25T17:14:45.030458+00:00
1
false
# Intuition\nAfter trying so many optimizations for the brute force approach, which tries to enumerate all the results after swapping nums[i] and nums[j], where i < j and see if it matches takes $$O(N^2.D^4)$$, where D = number of digits in a nums[x]. There are multipe approaches which optimizes this approach as well.\n\nHere, the idea is to store the all the enumerated results for each index (i) (which I am also calling as neighbors in my code) and check if they exist in the nums array for all j > i. This can be easily achieved by maintaing a hash map having frequencies of each number.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* Step 1. Build a frequency map.\n* Step 2. For each num, generate all the neighbors.\n* Step 3. Check if they exist in the frequency map.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N.D^4)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int N = nums.length;\n int count = 0;\n Map<Integer, Integer> freqMap = new HashMap<>();\n for (int num: nums) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n\n for (int num: nums) {\n int currNumFreq = freqMap.get(num);\n if (currNumFreq == 1) {\n freqMap.remove(num);\n } else {\n freqMap.put(num, currNumFreq - 1);\n }\n\n Set<Integer> neighbors = generateNeighbors(num);\n // System.out.println("num: " + num);\n // System.out.println("neighbors: " + neighbors);\n for (int neighbor: neighbors) {\n count += freqMap.getOrDefault(neighbor, 0);\n }\n }\n\n return count;\n }\n\n private Set<Integer> generateNeighbors(int num) {\n Set<Integer> set = new HashSet<>();\n set.add(num);\n String numStr = String.valueOf(num);\n int zeros = Math.min(7 - numStr.length(), 4);\n StringBuilder sb = new StringBuilder();\n for (int i = 0 ; i < zeros ; i++) {\n sb.append(\'0\');\n }\n\n sb.append(numStr);\n char numArr[] = sb.toString().toCharArray();\n int N = numArr.length;\n\n for (int i = 0 ; i < N ; i++) {\n for (int j = i + 1 ; j < N ; j++) {\n char temp = numArr[i];\n numArr[i] = numArr[j];\n numArr[j] = temp;\n\n // System.out.println(Integer.parseInt(new String(first)));\n int x = Integer.parseInt(new String(numArr));\n set.add(x);\n\n for (int k = 0 ; k < N ; k++) {\n for (int l = k + 1 ; l < N ; l++) {\n char temp1 = numArr[k];\n numArr[k] = numArr[l];\n numArr[l] = temp1;\n\n // System.out.println(Integer.parseInt(new String(first)));\n x = Integer.parseInt(new String(numArr));\n set.add(x);\n\n temp1 = numArr[k];\n numArr[k] = numArr[l];\n numArr[l] = temp1;\n }\n }\n\n temp = numArr[i];\n numArr[i] = numArr[j];\n numArr[j] = temp;\n }\n }\n\n return set;\n }\n}\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Easy Java solution, no fancy things
easy-java-solution-no-fancy-things-by-ka-nuzx
Intuition\n Describe your first thoughts on how to solve this problem. \nGenerate all numbers which could be generated using swapping 0, 1 or 2 times and add th
kartikeysemwal
NORMAL
2024-08-25T15:11:07.399787+00:00
2024-08-25T15:11:07.399831+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGenerate all numbers which could be generated using swapping 0, 1 or 2 times and add them to hashmap with freq. For the current number, check how many times it previously was seen and add it to answer.\n\n# Code\n```java []\nclass Solution {\n\n int getNum(char c[]) {\n int num = 0;\n int n = c.length;\n int prod = 1;\n for (int i = n - 1; i >= 0; i--) {\n num = num + (c[i] - \'0\') * prod;\n prod = prod * 10;\n }\n\n return num;\n }\n\n void swap(char c[], int x, int y) {\n char temp = c[x];\n c[x] = c[y];\n c[y] = temp;\n }\n\n void generate(char c[], int left, HashSet<Integer> set) {\n int n = c.length;\n\n int num = getNum(c);\n\n set.add(num);\n\n if (left == 0) {\n return;\n }\n\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n swap(c, i, j);\n\n generate(c, left - 1, set);\n\n swap(c, i, j);\n }\n }\n }\n\n public int countPairs(int[] nums) {\n int ans = 0;\n\n int n = nums.length;\n\n HashMap<Integer, Integer> map = new HashMap<>();\n\n for (int i = 0; i < n; i++) {\n int cur = nums[i];\n ans = ans + map.getOrDefault(cur, 0);\n\n HashSet<Integer> swapped = new HashSet<>();\n\n // append 0 to start to handle case like 1, 10, 100\n String curVal = String.valueOf(cur);\n while (curVal.length() < 8) {\n curVal = "0" + curVal;\n }\n\n generate(curVal.toCharArray(), 2, swapped);\n\n for (int swap : swapped) {\n map.put(swap, map.getOrDefault(swap, 0) + 1);\n }\n }\n\n return ans;\n }\n}\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
My Solution
my-solution-by-hope_ma-0k60
\n/**\n * Time Complexity: O(n * log(n) + n * (log(max_num) ^ 4))\n * Space Complexity: O(n_characters)\n * where `n` is the length of the vector `nums`\n *
hope_ma
NORMAL
2024-08-25T13:17:53.922400+00:00
2024-08-25T16:30:19.861166+00:00
2
false
```\n/**\n * Time Complexity: O(n * log(n) + n * (log(max_num) ^ 4))\n * Space Complexity: O(n_characters)\n * where `n` is the length of the vector `nums`\n * `max_num` is the maximum number of the vector `nums`\n * `n_characters` is the number of the characters\n * of the string representations\n * of all numbers of the vector `nums`\n */\nclass Solution {\n private:\n class Item {\n public:\n Item(const int num) : num_(num), s_num_(to_string(num)) {\n }\n \n bool operator<(const Item &rhs) const noexcept {\n return s_num_.size() < rhs.s_num_.size() || (s_num_.size() == rhs.s_num_.size() && num_ < rhs.num_);\n }\n \n bool operator==(const Item &rhs) const noexcept {\n return num_ == rhs.num_;\n }\n \n int num() const {\n return num_;\n }\n \n string s_num() const {\n return s_num_;\n }\n \n int length() const {\n return static_cast<int>(s_num_.size());\n }\n \n private:\n int num_;\n string s_num_;\n };\n \n public:\n int countPairs(const vector<int> &nums) {\n constexpr int base = 10;\n\n const int n = static_cast<int>(nums.size());\n map<Item, int> data;\n for (int i = 0; i < n; ++i) {\n ++data[Item(nums[i])];\n }\n \n const int max_length = data.rbegin()->first.length();\n int power10[max_length];\n power10[0] = 1;\n for (int i = 1; i < max_length; ++i) {\n power10[i] = power10[i - 1] * base;\n }\n \n unordered_map<int, int> num_to_count;\n int ret = 0;\n for (const auto &[item, count] : data) {\n ret += (count * (count - 1)) >> 1;\n unordered_set<int> seen({item.num()});\n string s_num(item.s_num());\n for (int i = 0; i < item.length() - 1; ++i) {\n for (int j = i + 1; j < item.length(); ++j) {\n const int swapped1 = item.num() +\n (s_num[j] - s_num[i]) * power10[item.length() - i - 1] +\n (s_num[i] - s_num[j]) * power10[item.length() - j - 1];\n do_count(swapped1, num_to_count, count, seen, ret);\n swap(s_num[i], s_num[j]);\n for (int k = i + 1; k < item.length() - 1; ++k) {\n for (int l = k + 1; l < item.length(); ++l) {\n const int swapped2 = swapped1 +\n (s_num[l] - s_num[k]) * power10[item.length() - k - 1] +\n (s_num[k] - s_num[l]) * power10[item.length() - l - 1];\n do_count(swapped2, num_to_count, count, seen, ret);\n }\n }\n swap(s_num[i], s_num[j]);\n }\n }\n num_to_count[item.num()] = count;\n }\n return ret;\n }\n \n private:\n void do_count(const int swapped,\n const unordered_map<int, int> &num_to_count,\n const int count,\n unordered_set<int> &seen,\n int &result) {\n if (seen.find(swapped) != seen.end()) {\n return;\n }\n \n seen.emplace(swapped);\n auto itr = num_to_count.find(swapped);\n result += itr == num_to_count.end() ? 0 : itr->second * count;\n }\n};\n```
0
0
[]
0
count-almost-equal-pairs-ii
Rust Solution
rust-solution-by-xiaoping3418-17qc
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
xiaoping3418
NORMAL
2024-08-25T12:29:02.884486+00:00
2024-08-25T12:29:02.884508+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```rust []\nuse std::collections::HashMap;\nuse std::collections::HashSet;\nimpl Solution {\n pub fn count_pairs(nums: Vec<i32>) -> i32 {\n let mut nums = nums;\n nums.sort();\n\n let mut mp = HashMap::<i32, i32>::new();\n let mut p = vec![1; 8];\n let mut ret = 0;\n\n for i in 1 .. 8 { p[i] = 10 * p[i - 1]; }\n for a in &nums {\n if let Some(cnt) = mp.get(a) {\n ret += *cnt;\n }\n *mp.entry(*a).or_insert(0) += 1;\n\n let mut s = HashSet::from([*a]); \n let m = Self::digits(*a);\n\n for i1 in 0 .. m {\n for i2 in i1 + 1 .. m {\n let b = Self::swap(*a, &p, i1, i2);\n if s.contains(&b) == false{\n if let Some(cnt) = mp.get(&b) { ret += *cnt; }\n s.insert(b); \n }\n for i3 in 0 .. m {\n for i4 in i3 + 1 .. m { \n let b = Self::swap(*a, &p, i1, i2);\n let b = Self::swap(b, &p, i3, i4);\n if s.contains(&b) == false {\n if let Some(cnt) = mp.get(&b) { ret += *cnt; }\n s.insert(b); \n } \n }\n }\n } \n }\n }\n ret\n }\n\n\n fn swap(a: i32, p: &Vec<i32>, i: usize, j: usize) -> i32 {\n let x = a / p[i] % 10;\n let y = a / p[j] % 10;\n a - x * p[i] - y * p[j] + y * p[i] + x * p[j] \n }\n\n\n fn digits(a: i32) -> usize {\n let mut a = a;\n let mut cnt = 0;\n while a > 0 {\n cnt += 1;\n a /= 10;\n }\n cnt\n }\n}\n```
0
0
['Rust']
0
count-almost-equal-pairs-ii
Intuitive solution though C++
intuitive-solution-though-c-by-informal0-gh4m
Intuition\nCalculate every value for every element in nums after swap at most twice, after that, you can get the number of element with same value within time c
informal007
NORMAL
2024-08-25T11:34:49.661485+00:00
2024-08-25T12:22:36.019017+00:00
2
false
# Intuition\nCalculate every value for every element in nums after swap at most twice, after that, you can get the number of element with same value within time complexity O(logN) using [multiset](https://en.cppreference.com/w/cpp/container/multiset)\n\n# Approach\nThe solution is intuitive. But several tips are worth to mentained to help you get AC\n1. Use int type to swap for every element to avoid TLE. if you tranfer that to string before swap and tranfer back to int, you will get TLE. I think that is because the memory capacity of int is equal with a char in string, the process of number in string format will increase extra momery and time consumption.\n2. Multiset can help to you get the amount with same value after swap position within time complexity of O(logN)\n3. Count for both (i, j) and (j, i) will help you to process the case of [2, 20], that can save lots of code and time for you.\n\n# Complexity\n- Time complexity:$O(C(7, 2) * C(7, 2) * N * logN)$ N=nums.length\n\n- Space complexity:$O(N)$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n multiset<int> appear_times;\n for(int i = 0; i < nums.size(); ++i) appear_times.insert(nums[i]);\n int result = 0;\n set<int> change_set;\n int base10_x = 1, base10_y = 1, base10_nx = 1, base10_ny = 1;\n for(int i = 0; i < nums.size(); ++i) {\n base10_x = 1;\n string s = to_string(nums[i]);\n for (int x = 0; x < s.size(); ++x) {\n base10_x *= 10;\n base10_y = base10_x;\n for (int y = x + 1; y < s.size(); ++y) {\n base10_y *= 10;\n // calculate the value after swap postion thought `int` type, it will be TLE if if you use int -> string -> swap -> int \n int x_pos_val = nums[i] % base10_x / (base10_x / 10);\n int y_pos_val = nums[i] % base10_y / (base10_y / 10);\n int change_val = nums[i] + x_pos_val * (base10_y / 10 - base10_x / 10) + y_pos_val * (base10_x / 10 - base10_y / 10);\n base10_nx = base10_x / 10;\n for (int nx = x; nx < s.size(); ++nx) {\n base10_nx *= 10;\n base10_ny = base10_nx;\n for (int ny = nx + 1; ny < s.size(); ++ny) {\n base10_ny *= 10;\n int nx_pos_val = change_val % base10_nx / (base10_nx / 10);\n int ny_pos_val = change_val % base10_ny / (base10_ny / 10);\n int change_val2 = change_val + nx_pos_val * (base10_ny / 10 - base10_nx / 10) + ny_pos_val * (base10_nx / 10 - base10_ny / 10);\n if(change_set.count(change_val2) == 0) {\n change_set.insert(change_val2);\n int increase_num = appear_times.count(change_val2);\n if(change_val2 == nums[i]) --increase_num;\n result += increase_num;\n if(((y == s.size() - 1 && x_pos_val == 0) || (ny == s.size() - 1 && nx_pos_val == 0))\n && !(x == nx && y == ny)) result += increase_num;\n }\n }\n }\n int change_val2 = change_val;\n if(change_set.count(change_val2) == 0) {\n change_set.insert(change_val2);\n int increase_num = appear_times.count(change_val2);\n if(change_val2 == nums[i]) --increase_num;\n result += increase_num;\n if(y == s.size() - 1 && x_pos_val == 0) result += increase_num;\n }\n }\n }\n change_set.clear();\n if (s.size() == 1) result += appear_times.count(nums[i]) - 1;\n }\n return result / 2;\n }\n};\n```\nIf this is unclear, let me know and I can make a video for you.\n\nIf this is helpful for you, upvote will be grateful.
0
0
['C++']
0
count-almost-equal-pairs-ii
ONLY SUGGESTION : This problem has a very tight time constraint!!
only-suggestion-this-problem-has-a-very-pth2x
Intuition\n Describe your first thoughts on how to solve this problem. \nFor each element calculate all the elements that could be created using two swaps of di
roshanbangar
NORMAL
2024-08-25T10:33:06.521364+00:00
2024-08-25T10:33:06.521405+00:00
47
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each element calculate all the elements that could be created using two swaps of digits. Rest of the comments in the code. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPlease check the comments. \n\n# Complexity\n- Time complexity:\n- (n * 2043)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n unordered_map<int, bool>mp;\n string adjust(string s) {\n string a = s;\n reverse(a.begin(), a.end());\n for(int i = 0; i < 7 - s.size(); i++) {\n a.push_back(\'0\');\n }\n reverse(a.begin(), a.end());\n return a;\n }\n // void add(int x) {\n // // adjust(x);\n // string a = to_string(x);\n // a = adjust(a);\n // for(int i = 0; i < a.size(); i++) {\n // for(int j = i + 1; j < a.size(); j++) {\n // swap(a[i], a[j]);\n // mp[x][stoi(a)] = true;\n // for(int l = 0; l < a.size(); l++) {\n // for(int m = l + 1; m < a.size(); m++) {\n // swap(a[l], a[m]);\n // mp[x][stoi(a)] = true;\n // swap(a[l], a[m]);\n // }\n // }\n // swap(a[i], a[j]);\n // }\n // }\n // }\n int countPairs(vector<int>& nums) {\n mp.clear();\n // for(auto x : nums) {\n // add(x);\n // }\n long long ans = 0;\n unordered_map<int, int>mp1;\n \n \n for(int i = 0; i < nums.size(); i++) {\n\n {\n int x = nums[i];\n mp.clear();\n string a = to_string(x);\n a = adjust(a);\n for(int i = 0; i < a.size(); i++) {\n for(int j = i + 1; j < a.size(); j++) {\n swap(a[i], a[j]);\n mp[stoi(a)] = true;\n for(int l = 0; l < a.size(); l++) {\n for(int m = l + 1; m < a.size(); m++) {\n swap(a[l], a[m]);\n mp[stoi(a)] = true;\n swap(a[l], a[m]);\n }\n }\n swap(a[i], a[j]);\n }\n }\n }\n\n\n\n for(auto x : mp) {\n ans += mp1[x.first];\n }\n mp1[nums[i]]++;\n }\n // for(auto x : nums) {\n // ans += (mp1[x] - 1);\n // }\n // ans /= 2;\n return ans;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Easy C++ Code with Comments for better understanding.
easy-c-code-with-comments-for-better-und-31ix
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
spidycoder178
NORMAL
2024-08-25T09:49:52.270465+00:00
2024-08-25T09:49:52.270509+00:00
32
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n // Function to make num containing count of digits as \'digits\'.\n string makeEqual(int num, int digits) {\n string t = to_string(num);\n // If a string has smaller size then adding leading 0 to make it the same size as others.\n while (t.size() < digits) {\n t = "0" + t;\n }\n return t;\n }\n\n // Making all possible swaps for number num.\n // TC: O(7^4) as digits in num at most 7 and two swaps will be performed using 7^4 which is constant and small.\n unordered_set<string> makeSwap(int num, int digits) {\n // First making it of the same size as others.\n string t = makeEqual(num, digits);\n unordered_set<string> st;\n st.insert(t);\n // Performing all possible swaps.\n for (int i = 0; i < t.size(); i++) {\n for (int j = i + 1; j < t.size(); j++) {\n swap(t[i], t[j]);\n // Inserting the first swapped string into the set.\n st.insert(t);\n // Second swap on the first swapped string.\n for (int i1 = 0; i1 < t.size(); i1++) {\n for (int j1 = i1 + 1; j1 < t.size(); j1++) {\n swap(t[i1], t[j1]);\n // Inserting into the set.\n st.insert(t);\n // Reverting the second swap to the previous string so that another swap can be performed.\n swap(t[i1], t[j1]);\n }\n }\n // Reverting the first swap.\n swap(t[i], t[j]);\n }\n }\n return st;\n }\n\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n int ans = 0;\n int maxi = 0;\n \n // Find the maximum number of digits in the numbers.\n for (auto it : nums) {\n string t = to_string(it);\n maxi = max(maxi, (int)t.size());\n }\n \n unordered_map<int, int> mp;\n for (int i = 0; i < n; i++) {\n // After making all possible swaps for nums[i].\n for (auto &it : makeSwap(nums[i], maxi)) {\n int val = stol(it);\n // Checking if any number is present in the map or not.\n if (mp.count(val)) ans += mp[val];\n }\n // Inserting into map.\n mp[nums[i]]++;\n }\n return ans;\n }\n};\n\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
😂There's NO N*M^4 solution ,Passed N*M^5
theres-no-nm4-solution-passed-nm5-by-sam-n7gz
Reason\n Describe your first thoughts on how to solve this problem. \nall of u will have ignored complexity of either comparing string or inserting numbers of s
sameonall
NORMAL
2024-08-25T09:49:17.004179+00:00
2024-08-27T16:09:36.402697+00:00
22
false
# Reason\n<!-- Describe your first thoughts on how to solve this problem. -->\nall of u will have ignored complexity of either comparing string or inserting numbers of string into a set or interconversion, which is basically O(length of the string)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n*m^5)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n+m^4)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass Solution {\npublic:\n\n int countPairs(vector<int>& nums) {\n int count = 0;\n unordered_map<int,int>mp;\n int maxLen=to_string(nums[0]).length();\n mp[nums[0]]++;\n for (int i = 1; i < nums.size(); ++i) {\n string t=to_string(nums[i]);\n int l=t.length();\n maxLen=max(maxLen,l);\n int len=maxLen-l;string s=t;\n string c="";\n for(int j=0;j<len;j++)c+="0";\n s=c+s;\n unordered_map<int,bool>seen;\n for(int j=0;j<s.length();j++){\n for(int k=j;k<s.length();k++){\n string t=s;\n swap(t[j],t[k]);\n for(int l=j;l<s.length();l++){\n for(int m=l;m<s.length();m++){\n string tt=t;\n swap(tt[l],tt[m]);\n int y=stoi(tt);\n if(seen.count(y))continue;\n count+=mp[y];\n seen[y]=true;\n }\n }\n }\n }\n mp[nums[i]]++;\n }\n return count;\n }\n\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Brute Force || O(N*7*7*7*7)
brute-force-on7777-by-ameynaik09-4q9e
Intuition\n Describe your first thoughts on how to solve this problem. \nFor each number take a hashmap of all the values that can be formed by applying either
ameynaik09
NORMAL
2024-08-25T09:11:54.946904+00:00
2024-08-25T09:11:54.946933+00:00
49
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each number take a hashmap of all the values that can be formed by applying either one or two operations. Then simaltaneously check all that values whether have occured in the nums till now if yes add their freq to your main ans. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N*(7^4))\n N for iteration and 4 loops on max digit size of 7 and extraction complexity of unordered_map O(1).\n\n# Code\n```cpp []\nclass Solution {\npublic:\n unordered_map<string,int>dp;\n string makeDigit(int num, int digits) {//func for digitmakeup\n string s = to_string(num);\n int n = s.size();\n for(int i=0;i<digits-n;i++)\n s = "0" + s;\n return s;\n }\n unordered_map<string,int>getnums(int num,int digits_makeup){\n string s = makeDigit(num,digits_makeup);\n unordered_map<string,int>mp;\n mp[s]++;\n for(int i = 0; i < s.length(); i++){\n for(int j = i + 1; j < s.length(); j++){\n swap(s[i],s[j]);\n mp[s]++;\n for(int k = 0; k < s.length(); k++){\n for(int l = k + 1; l < s.length(); l++){\n if(s[k]!=s[l]){\n swap(s[k],s[l]);\n mp[s]++;\n swap(s[k],s[l]);\n }\n }\n }\n swap(s[i],s[j]);\n }\n }\n return mp;\n }\n int countPairs(vector<int>& nums) {\n // O(N*49*49) here\n int n=nums.size();\n int digits_makeup = to_string(*max_element(nums.begin(),nums.end())).size();\n int ans=0;\n for(int i=0;i<nums.size();i++){\n for(auto s:getnums(nums[i],digits_makeup)){\n if(dp.count(s.first)){\n ans+=dp[s.first];\n }\n }\n dp[makeDigit(nums[i],digits_makeup)]++;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Simple and easy solution (100% memory and time beats)
simple-and-easy-solution-100-memory-and-ikd52
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Meet_Khanpara
NORMAL
2024-08-25T08:02:51.074958+00:00
2024-08-25T08:02:51.074997+00:00
27
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N^2)\n\n# Code\n```java []\nclass Solution {\n public boolean ist(int a, int b) {\n String s = Integer.toString(a);\n String s1 = Integer.toString(b);\n \n // Ensure s is the shorter or same length string\n if (s.length() > s1.length()) {\n String temp = s;\n s = s1;\n s1 = temp;\n }\n \n // Pad the shorter string with leading zeros\n StringBuilder sb = new StringBuilder(s);\n while (sb.length() < s1.length()) {\n sb.insert(0, \'0\');\n }\n s = sb.toString();\n\n int cnt = 0;\n int[] f1 = new int[10];\n int[] f2 = new int[10];\n List<Integer> diffIndices = new ArrayList<>();\n\n for (int i = 0; i < s.length(); i++) {\n f1[s.charAt(i) - \'0\']++;\n f2[s1.charAt(i) - \'0\']++;\n if (s.charAt(i) != s1.charAt(i)) { \n cnt++;\n diffIndices.add(i);\n }\n }\n\n if (!Arrays.equals(f1, f2)) return false;\n if (cnt == 0 || cnt == 2 || cnt == 3) return true;\n\n if (cnt == 4) {\n int a1 = diffIndices.get(0);\n int b1 = diffIndices.get(1);\n int c1 = diffIndices.get(2);\n int d1 = diffIndices.get(3);\n\n return (s.charAt(a1) == s1.charAt(b1) && s.charAt(b1) == s1.charAt(a1) && s.charAt(c1) == s1.charAt(d1) && s.charAt(d1) == s1.charAt(c1)) ||\n (s.charAt(a1) == s1.charAt(c1) && s.charAt(c1) == s1.charAt(a1) && s.charAt(b1) == s1.charAt(d1) && s.charAt(d1) == s1.charAt(b1)) ||\n (s.charAt(a1) == s1.charAt(d1) && s.charAt(d1) == s1.charAt(a1) && s.charAt(b1) == s1.charAt(c1) && s.charAt(c1) == s1.charAt(b1)) ||\n (s1.charAt(a1) == s.charAt(b1) && s1.charAt(b1) == s.charAt(a1) && s1.charAt(c1) == s.charAt(d1) && s1.charAt(d1) == s.charAt(c1)) ||\n (s1.charAt(a1) == s.charAt(c1) && s1.charAt(c1) == s.charAt(a1) && s1.charAt(b1) == s.charAt(d1) && s1.charAt(d1) == s.charAt(b1)) ||\n (s1.charAt(a1) == s.charAt(d1) && s1.charAt(d1) == s.charAt(a1) && s1.charAt(b1) == s.charAt(c1) && s1.charAt(c1) == s.charAt(b1));\n }\n\n return false;\n }\n\n public int countPairs(int[] nums) {\n int ans = 0;\n Map<Integer, Integer> m = new HashMap<>();\n\n for (int num : nums) {\n m.put(num, m.getOrDefault(num, 0) + 1);\n }\n\n List<Integer> uniqueNums = new ArrayList<>(m.keySet());\n \n for (int count : m.values()) {\n ans += (count * (count - 1)) / 2;\n }\n\n int n = uniqueNums.size();\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (ist(uniqueNums.get(i), uniqueNums.get(j))) {\n ans += (m.get(uniqueNums.get(i)) * m.get(uniqueNums.get(j)));\n }\n }\n }\n\n return ans;\n }\n}\n\n```
0
0
['String', 'Java']
0
count-almost-equal-pairs-ii
JAVA || Faster than 100% || Intuitive Approach || Extending the easir variant code ||
java-faster-than-100-intuitive-approach-y7xyc
Intuition\n Describe your first thoughts on how to solve this problem. \nIntuition was keeping track of indexes where corresponding values in num1 and num2 has
ManjeetYadav36
NORMAL
2024-08-25T06:52:47.142203+00:00
2024-08-25T06:52:47.142241+00:00
25
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition was keeping track of indexes where corresponding values in num1 and num2 has a mismatch.\nIn easier variant when only one swap was allowed, if we have exactly 2 pairs of such indexes, we can check whether they can be wapped to make a matach, example 127 and 172, here there are 2 mismatch, in num1 there is 2 while in num2 there is 7 this means we got a mismatch pair (2,7) , similarly next pair will be (7,2). now we have to check whethere we can do a swap do make them matach, and (a,b) ,(c,d) , after swap it will be (a,d) and (b, c) applying it here it would be (2,2) and(7,7). This approach works when atmost 1 swap\n\nIn this version, we can have atmost 2 swaps, \nMeaning either 0 or 1 or 2 swaps, \n1 swap case has been discussed, when there are 2 pairs of mismatch, \nfor 2 swaps, we either need 3 pairs or 4 pairs of mismatch. \nif there are more than 4 mismatch pairs, they cant be matched.\n\nIf we got 4 pairs, we must be able to group these pairs in group of 2 and 2 and check if they can be swapped to make same\n\nIf we got 3 pairs, checking the frequency of digits of pairs will do the job\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n# Complexity\n- Time complexity:O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(1)\n\n\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int n = nums.length;\n int count = 0;\n \n for (int k = 0; k < n; k++) {\n for (int j = k + 1; j < n; j++) {\n int x = nums[k];\n int y = nums[j];\n \n if (x == y) {\n count++;\n } else {\n String num1 = String.valueOf(x);\n String num2 = String.valueOf(y);\n \n \n if (num1.length() != num2.length()) {\n while (num1.length() < num2.length()) num1 = "0" + num1;\n while (num2.length() < num1.length()) num2 = "0" + num2;\n }\n \n int len = num1.length();\n int diff = 0;\n int[] a1 = new int[4];\n int[] a2 = new int[4];\n boolean possible=true;\n for (int p = 0; p < len; p++) {\n int c1 = num1.charAt(p) - \'0\';\n int c2 = num2.charAt(p) - \'0\';\n if (c1 != c2) {\n if(diff==4) {\n possible=false;\n break;\n }\n a1[diff] = c1;\n a2[diff] = c2;\n diff++;\n }\n }\n if(possible){\n if (diff == 2) {\n if (a1[0] == a2[1] && a1[1] == a2[0]) count++;\n } else if (diff == 3) {\n int []f=new int[10];\n for(int i=0;i<diff;i++){\n f[a1[i]]++;\n f[a2[i]]--;\n }\n boolean canbe=true;\n for(int i=0;i<10;i++) if(f[i]!=0) canbe=false;\n if(canbe) count++;\n }\n else if(diff==4){\n for(int i=1;i<4;i++){\n if(a1[0]==a2[i] && a1[i]==a2[0]){\n if(i==1 && a1[2]==a2[3] && a1[3]==a2[2]) {count++ ; break;}\n else if(i==2 && a1[1]==a2[3] && a1[3]==a2[1]) {count++ ; break;}\n else if(i==3 && a1[1]==a2[2] && a1[2]==a2[1]) {count++; break;}\n }\n }\n }\n }\n }\n }\n }\n return count;\n }\n}\n\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Python || 100% Beats || Simple solution
python-100-beats-simple-solution-by-vila-7ari
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
vilaparthibhaskar
NORMAL
2024-08-25T06:41:15.534751+00:00
2024-08-25T06:41:15.534789+00:00
37
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n c = Counter(nums)\n ans = 0\n nums = list(set(nums))\n for i in nums:\n hold = str(i)\n l = len(hold)\n s = set([i])\n for j in range(l):\n for k in range(j + 1, l):\n temp = hold[:j] + hold[k] + hold[j + 1:k] + hold[j] + hold[k + 1:]\n mid = int(temp)\n if mid not in s and mid in c and mid < i:\n ans += (c[i] * c[mid])\n s.add(mid)\n for m in range(l):\n for n in range(m + 1, l):\n cur = temp[:m] + temp[n] + temp[m + 1:n] + temp[m] + temp[n + 1:]\n cur = int(cur)\n if cur in s or cur >= i:continue\n s.add(cur)\n ans += (c[i] * c[cur])\n for i in c.values():\n ans += ((i) * (i - 1)) // 2\n return ans\n```
0
0
['Hash Table', 'Python3']
0
count-almost-equal-pairs-ii
Trie fun
trie-fun-by-kamanashisroy-sfdz
Intuition\nIf a is matching with b, then be is matching with a too. \nSo if we calculate all matches (a,b and b,a)and then divide by 2, we get the result.\n\nTo
kamanashisroy
NORMAL
2024-08-25T06:16:26.477897+00:00
2024-08-25T06:16:26.477929+00:00
59
false
# Intuition\nIf a is matching with b, then be is matching with a too. \nSo if we calculate all matches (a,b and b,a)and then divide by 2, we get the result.\n\nTo reduce the branches while searching we can use trie . We can put the original values in the nums in the trie first.\n\nNow during the exploration of the swap values, we can find the matches in the trie that contains original values.\n\n# Approach\n\nUsing the trie is just like a dictionary or hash-table.\n\nWe have just put our matches in the trie/hash-table.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```python3 []\n\nclass Trie:\n def __init__(self, val):\n self.val = val\n self.child = [None]*10\n self.content = set()\n self.contentDgts = None\n self.matches = set()\n \n def pushKey(self, dgts, idx):\n cur = self\n for x in dgts:\n if cur.child[x] is None:\n cur.child[x] = Trie(x)\n cur = cur.child[x]\n cur.content.add(idx)\n cur.contentDgts = dgts\n \n def pushPairRecursive(self, dgts, pos, idx, pos1, pos2):\n\n if pos >= len(dgts):\n # no more room\n if len(self.content):\n self.matches.add(idx)\n return\n \n spos = pos\n if pos2 is not None:\n if pos2 == spos:\n spos = pos1\n \n if self.child[dgts[spos]] is not None:\n self.child[dgts[spos]].pushPairRecursive(dgts,pos+1,idx,pos1, pos2)\n \n if pos1 is None:\n # we can swap pos as pos1, with some pos2\n for pos2 in range(pos+1,len(dgts)):\n if self.child[dgts[pos2]] is not None:\n self.child[dgts[pos2]].pushPairRecursive(dgts,pos+1,idx,pos, pos2)\n \n def pushPair(self, dgts, idx):\n cur = self\n for x in dgts:\n if cur.child[x] is None:\n return\n cur = cur.child[x]\n cur.matches.add(idx)\n \n def find(self, dgts):\n cur = self\n for i,x in enumerate(dgts):\n if cur.child[x] is None:\n return None\n cur = cur.child[x]\n \n return cur\n \n def dump(self):\n if len(self.content):\n print(self.contentDgts,self.matches)\n for i,x in enumerate(self.child):\n if x is not None:\n x.dump()\n \n def iterAll(self):\n stack = [self]\n while stack:\n cur = stack.pop()\n if len(cur.content) and len(cur.matches):\n yield cur\n for x in cur.child:\n if x is not None:\n stack.append(x)\n \nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n \n\n def calcDigits(given, givenSz = 0):\n ret = []\n while given:\n given,digit = divmod(given,10)\n ret.append(digit)\n \n while len(ret) < givenSz:\n ret.append(0)\n return ret\n\n biggest = max(nums)\n SZ = len(calcDigits(biggest))\n\n dgtList = [None]*len(nums)\n tri = Trie(None)\n for i,x in enumerate(nums):\n digits = calcDigits(x, SZ)\n dgtList[i] = digits\n tri.pushKey(digits, i)\n \n for i,x in enumerate(nums):\n digits = dgtList[i]\n tri.pushPair(digits,i) \n for ii in range(SZ):\n for jj in range(ii+1,SZ):\n if digits[ii] != digits[jj]:\n digits2 = digits[:]\n digits2[ii] = digits[jj]\n digits2[jj] = digits[ii]\n tri.pushPairRecursive(digits2,0,i,None,None) \n \n #tri.dump()\n result = 0\n for node in tri.iterAll():\n result += (len(node.matches)-1)*(len(node.content))\n #result += (vv*(vv-1))>>1\n \n return result>>1\n```
0
0
['Python3']
1
count-almost-equal-pairs-ii
Java Passes beats 100% but same code TLE in C++
java-passes-beats-100-but-same-code-tle-5m34k
Complexity\n- Time complexity: O(n^2 * 7) \n\n- Space complexity: O(1) \n\nC++ []\n// TLE 625/630 same logic passes in Java\nclass Solution {\npublic:\n int
nitinsrichakri
NORMAL
2024-08-25T05:39:52.801032+00:00
2024-08-25T05:39:52.801068+00:00
12
false
# Complexity\n- Time complexity: $$O(n^2 * 7)$$ \n\n- Space complexity: $$O(1)$$ \n\n``` C++ []\n// TLE 625/630 same logic passes in Java\nclass Solution {\npublic:\n int countPairs(vector<int>& a) {\n int n=a.size(),ans=0;\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++)\n {\n int y=a[j],x=a[i],ok=0;\n vector<int> dx,dy;\n while(x + y){\n if(x%10!=y%10){dx.push_back(x%10);dy.push_back(y%10);ok++;}\n x/=10;y/=10;\n }\n if(ok==0)ans++;\n if(ok==2){\n if(dx[0]==dy[1] && dx[1]==dy[0])ans++;\n }\n if(ok==3){\n sort(dx.begin(),dx.end());\n sort(dy.begin(),dy.end());\n if(dx==dy)ans++;\n }\n if(ok==4){\n if(dx[0]==dy[1] && dx[1]==dy[0] && dx[2]==dy[3] && dx[3]==dy[2])ans++;\n else if(dx[0]==dy[2] && dx[1]==dy[3] && dx[2]==dy[0] && dx[3]==dy[1])ans++;\n else if(dx[0]==dy[3] && dx[1]==dy[2] && dx[2]==dy[1] && dx[3]==dy[0])ans++;\n }\n } \n }\n return ans;\n }\n};\n```\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] a) {\n int n = a.length, ans = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n int y = a[j], x = a[i], ok = 0;\n int[] dx = new int[4], dy = new int[4];\n int idx = 0;\n \n while (x + y > 0) {\n if (x % 10 != y % 10) {\n \n if(idx==4){\n idx=-1;\n break;\n }\n dx[idx] = x % 10;\n dy[idx] = y % 10;\n ok++;\n idx++;\n }\n x /= 10;\n y /= 10;\n }\n if(idx==-1)continue;\n\n if (ok == 0) {\n ans++;\n continue;\n }\n \n if (ok == 2) {\n if (dx[0] == dy[1] && dx[1] == dy[0]) ans++;\n } else if (ok == 3) {\n Arrays.sort(dx, 0, 3);\n Arrays.sort(dy, 0, 3);\n if (Arrays.equals(dx, dy)) ans++;\n } else if (ok == 4) {\n if (dx[0] == dy[1] && dx[1] == dy[0] && dx[2] == dy[3] && dx[3] == dy[2]) ans++;\n else if (dx[0] == dy[2] && dx[1] == dy[3] && dx[2] == dy[0] && dx[3] == dy[1]) ans++;\n else if (dx[0] == dy[3] && dx[1] == dy[2] && dx[2] == dy[1] && dx[3] == dy[0]) ans++;\n }\n }\n }\n return ans;\n }\n}\n\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
hehehehehe
hehehehehe-by-priyanshu_gupta_9620-6zls
Code\ncpp []\nclass Solution {\npublic:\n string tostg(int a){\n string ans="";\n while(a){\n ans+=(\'0\'+(a%10));\n a/=1
Priyanshu_gupta_9620
NORMAL
2024-08-25T05:33:23.143757+00:00
2024-08-25T05:33:23.143774+00:00
84
false
# Code\n```cpp []\nclass Solution {\npublic:\n string tostg(int a){\n string ans="";\n while(a){\n ans+=(\'0\'+(a%10));\n a/=10;\n }\n return ans;\n }\n int countPairs(vector<int>& nums) {\n map<int,int> mp;\n vector<string> v;\n int maxi=*max_element(nums.begin(),nums.end());\n string chk=tostg(maxi);\n int maxsz=chk.size();\n // int maxsz = 7;\n for(auto it:nums){\n string s1=tostg(it);\n int diff=maxsz-s1.size();\n while(diff--){\n s1+=\'0\';\n }\n reverse(s1.begin(),s1.end());\n mp[it]++;\n v.push_back(s1);\n }\n // for(auto it:v){cout<<it<<\' \';}\n // cout<<endl;\n // cout<<endl;\n // for(auto it:mp){\n // cout<<it.first<<\' \'<<it.second<<endl;\n // }\n int sz=maxsz;\n int ans=0;\n for(auto it:v){\n string s=it;\n \n mp[stoi(s)]--;\n // set<string> st;\n set<int> st;\n st.insert(stoi(s));\n for(int i=0;i<sz;i++){\n for(int j=i+1;j<sz;j++){\n\n string s2=s;\n if(s2[i] == s2[j])\n {\n continue;\n }\n\n swap(s2[i],s2[j]);\n\n st.insert(stoi(s2));\n\n for(int k=0;k<sz;k++){\n for(int l=k+1;l<sz;l++){\n if(min(k,l) == min(i,j) && max(k,l) == max(i,j))\n {\n continue;\n }\n string s3 = s2;\n if(s3[k] == s3[l])\n {\n continue;\n }\n swap(s3[k],s3[l]);\n st.insert(stoi(s3));\n }\n }\n }\n }\n for(auto it:st){\n ans+=mp[it];\n }\n }\n return ans;\n \n }\n \n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Java HashMap Sort
java-hashmap-sort-by-mot882000-1ljj
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
mot882000
NORMAL
2024-08-25T05:18:43.705970+00:00
2024-08-25T05:18:43.705999+00:00
33
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n\n List<Set<Integer>> list = new ArrayList<Set<Integer>>();\n\n Arrays.sort(nums);\n for(int i = 0; i < nums.length; i++) list.add(new HashSet<Integer>());\n\n Map<Integer, Integer> map = new HashMap<Integer, Integer>();\n\n for(int i = 0; i < nums.length; i++) {\n map.put(nums[i], map.getOrDefault(nums[i], 0)+1);\n char c1[] = String.valueOf(nums[i]).toCharArray();\n list.get(i).add(nums[i]);\n for(int a = 0; a < c1.length; a++) {\n for(int b = a; b < c1.length; b++) {\n swap(c1,a,b);\n int num = 0;\n int de = 1;\n for(int k = c1.length-1; k >= 0; k--) {\n num += de * (int)(c1[k]-\'0\');\n de *= 10;\n }\n list.get(i).add(num);\n\n for(int c = 0; c < c1.length; c++) {\n for(int d = 0; d < c1.length; d++) {\n swap(c1,c,d);\n num = 0;\n de = 1;\n for(int k = c1.length-1; k >= 0; k--) {\n num += de * (int)(c1[k]-\'0\');\n de *= 10;\n }\n list.get(i).add(num);\n swap(c1,c,d);\n }\n }\n swap(c1,a,b);\n }\n }\n }\n\n\n int result = 0;\n\n \n // System.out.println(map);\n for(int i = nums.length-1 ; i >= 0; i--) {\n // System.out.println(list.get(i));\n for(int key : list.get(i) ) {\n result += map.getOrDefault(key,0);\n }\n result--;\n int cnt = map.get(nums[i]);\n if ( cnt == 1 ) map.remove(nums[i]);\n else map.put(nums[i], cnt-1);\n }\n\n return result;\n }\n\n private void swap(char c[], int a, int b) {\n char temp = c[a];\n c[a] = c[b];\n c[b] = temp;\n }\n}\n```
0
0
['Hash Table', 'Sorting', 'Java']
0
count-almost-equal-pairs-ii
Java HashMap Sort
java-hashmap-sort-by-mot882000-2r4x
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
mot882000
NORMAL
2024-08-25T05:16:12.729398+00:00
2024-08-25T05:16:12.729419+00:00
17
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n\n List<Set<Integer>> list = new ArrayList<Set<Integer>>();\n\n Arrays.sort(nums);\n for(int i = 0; i < nums.length; i++) list.add(new HashSet<Integer>());\n\n Map<Integer, Integer> map = new HashMap<Integer, Integer>();\n\n for(int i = 0; i < nums.length; i++) {\n map.put(nums[i], map.getOrDefault(nums[i], 0)+1);\n char c1[] = String.valueOf(nums[i]).toCharArray();\n list.get(i).add(nums[i]);\n for(int a = 0; a < c1.length; a++) {\n for(int b = a; b < c1.length; b++) {\n swap(c1,a,b);\n int num = 0;\n int de = 1;\n for(int k = c1.length-1; k >= 0; k--) {\n num += de * (int)(c1[k]-\'0\');\n de *= 10;\n }\n list.get(i).add(num);\n\n for(int c = 0; c < c1.length; c++) {\n for(int d = 0; d < c1.length; d++) {\n swap(c1,c,d);\n num = 0;\n de = 1;\n for(int k = c1.length-1; k >= 0; k--) {\n num += de * (int)(c1[k]-\'0\');\n de *= 10;\n }\n list.get(i).add(num);\n swap(c1,c,d);\n }\n }\n swap(c1,a,b);\n }\n }\n }\n\n\n int result = 0;\n\n \n // System.out.println(map);\n for(int i = nums.length-1 ; i >= 0; i--) {\n // System.out.println(list.get(i));\n for(int key : list.get(i) ) {\n result += map.getOrDefault(key,0);\n }\n result--;\n int cnt = map.get(nums[i]);\n if ( cnt == 1 ) map.remove(nums[i]);\n else map.put(nums[i], cnt-1);\n }\n\n return result;\n }\n\n private void swap(char c[], int a, int b) {\n char temp = c[a];\n c[a] = c[b];\n c[b] = temp;\n }\n}\n```
0
0
['Hash Table', 'Sorting', 'Java']
0
count-almost-equal-pairs-ii
Easy Solution :)
easy-solution-by-user20222-8iih
Code\ncpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n int count = 0;\n unordered_map<in
user20222
NORMAL
2024-08-25T05:13:50.632226+00:00
2024-08-25T05:13:50.632258+00:00
66
false
# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n int count = 0;\n unordered_map<int,int>mp;\n for(auto&it:nums)mp[it]++; \n vector<vector<int>> pos(n);\n for (int i = 0; i < n; ++i) {\n pos[i] = f(nums[i]); \n } \n for (int i = 0; i < n; ++i) {\n mp[nums[i]]--;\n if(mp[nums[i]]==0)mp.erase(nums[i]);\n for (int j = 0; j < pos[i].size(); ++j) {\n if(mp.find(pos[i][j])!=mp.end())count+=mp[pos[i][j]];\n } \n }\n return count;\n }\n private:\n vector<int> f(int num) {\n unordered_set<int>rev;\n string s = to_string(num);\n reverse(s.begin(),s.end());\n for(int i=s.size();i<7;i++)s.push_back(\'0\');\n reverse(s.begin(),s.end());\n int len = s.length();\n rev.insert(num);\n for (int i = 0; i < len; ++i) {\n for (int j = i + 1; j < len; ++j) {\n swap(s[i], s[j]);\n int num = stoi(s); \n for (int ii = 0; ii < len; ++ii) {\n for (int jj = ii + 1; jj < len; ++jj) {\n swap(s[ii], s[jj]);\n int num = stoi(s);\n rev.insert(num);\n swap(s[ii], s[jj]);\n }\n } \n rev.insert(num);\n swap(s[i], s[j]);\n }\n } \n vector<int>v;\n for(auto&it:rev)v.push_back(it);\n return v;\n };\n}; \n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Bruteforce Rust
bruteforce-rust-by-do7and-phvk
\n# Complexity\n- Time complexity:O(n^2)\n Add your time complexity here, e.g. O(n) \n\n\n# Code\nrust []\n\nimpl Solution {\n pub fn count_pairs(nums: Vec<i
do7and
NORMAL
2024-08-25T05:03:53.843169+00:00
2024-08-25T05:03:53.843197+00:00
18
false
\n# Complexity\n- Time complexity:$$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```rust []\n\nimpl Solution {\n pub fn count_pairs(nums: Vec<i32>) -> i32 {\n fn check(mut a:i32,mut b:i32)-> bool {\n if (a == b) {return true;}\n let mut flag = 0;\n let mut flaga = -1;\n let mut flagb = -1;\n let mut flagc = -1;\n let mut flagd = -1;\n let mut flage = -1;\n let mut flagf = -1;\n let mut flagg = -1;\n let mut flagh = -1;\n while !(a == 0 && b == 0){\n if a %10 == b%10{\n \n }else{\n if flag == 1{\n flagc = a %10;\n flagd = b%10;\n flag = 2;\n \n }else if flag == 4{\n return false;\n }else if flag == 3{\n flagg = a %10;\n flagh = b%10;\n flag = 4;\n }else if flag == 2{\n flage = a %10;\n flagf = b%10;\n flag = 3;\n }else if flag == 0{\n flaga = a %10;\n flagb = b%10;\n flag = 1;\n }else{\n return false;\n }\n }\n a = a/10;\n b = b/10;\n }\n \n if (flag == 2){\n return (flaga == flagd && flagb== flagc);\n }else if (flag == 3){\n return (flaga == flagd && flagb== flage && flagf == flagc)||(flaga == flagf && flagb== flagc && flage == flagd );\n \n }else{\n //a c e g\n //b d f h\n return (flaga == flagd && flagb== flagc && flage == flagh && flagg== flagf)||(flaga == flagf && flagb== flage && flagc == flagh && flagg== flagd)||(flaga == flagh && flagb== flagg && flagc == flagf && flagd== flage);\n }\n \n }\n let mut ans = 0;\n for i in 0..nums.len(){\n for j in i+1..nums.len(){\n if check(nums[i] ,nums[j]){\n ans += 1;\n }\n }\n }\n ans\n }\n}\n```
0
0
['Rust']
0
count-almost-equal-pairs-ii
Almost linear python solution : O(N) * (7^4)
almost-linear-python-solution-on-74-by-u-x5dv
Intuition\n Describe your first thoughts on how to solve this problem. \nFirst you need to zfill all nums to max num len.\n\nWe are going to create all posible
utkarshkolhe
NORMAL
2024-08-25T05:01:41.833403+00:00
2024-08-25T05:01:41.833422+00:00
57
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst you need to zfill all nums to max num len.\n\nWe are going to create all posible 2 level swaps which would be at most 7^4. because number is less than 10^7.\n\nWe then go reverse on our nums array creating counter dictionary and for every single number we check if its potential swaps exists in our dictionary.\n\n# Complexity\n- Time complexity: O(n *(7^4)) = O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n def rec(num1):\n ans=set()\n ans.add(num1)\n n=len(num1)\n for i in range(n):\n for j in range(n):\n newnum= list(num1)\n newnum[i],newnum[j]=newnum[j],newnum[i]\n ans.add("".join(newnum))\n for num in list(ans):\n for i in range(n):\n for j in range(n):\n newnum= list(num)\n newnum[i],newnum[j]=newnum[j],newnum[i]\n ans.add("".join(newnum))\n return ans \n\n counter= defaultdict(lambda:0)\n l=len(str(max(nums)))\n ans=0\n for num in nums[::-1]:\n num1=str(num)\n if len(num1)<l:\n num1 = ("0"*(l-len(num1)))+num1\n arr=rec(num1)\n for r in arr:\n ans+=counter[r]\n counter[num1]+=1\n \n\n return ans\n```
0
0
['Python3']
0
count-almost-equal-pairs-ii
Sometimes brute force works.
sometimes-brute-force-works-by-jccccc-pujf
Intuition\n Describe your first thoughts on how to solve this problem. \nCheck each pair with brute force. Not a fancy solution though.\n# Approach\n Describe y
jccccc
NORMAL
2024-08-25T04:47:38.110780+00:00
2024-08-25T04:47:38.110799+00:00
26
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck each pair with brute force. Not a fancy solution though.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n- Time complexity:$$O(n^2)$$\n\n- Space complexity:$$O(1)$$\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n int res = 0;\n int len = nums.length;\n for (int i = 0; i < len; ++i) {\n for (int j = i+1; j < len; ++j) {\n if (good(nums[i], nums[j])) {\n ++res;\n }\n }\n }\n return res;\n }\n\n boolean good(int a, int b) {\n if (a == b) return true;\n int[] ofA = new int[4];\n int[] ofB = new int[4];\n int i = 0;\n while (a > 0 || b > 0) {\n int aLast = a % 10;\n a /= 10;\n int bLast = b % 10;\n b /= 10;\n if (aLast != bLast) {\n if (i >=4) return false;\n ofA[i] = aLast;\n ofB[i] = bLast;\n ++i;\n }\n }\n\n return exchange(ofA, ofB, 0, 0) <= 2;\n }\n\n int exchange(int[] ofA, int[] ofB, int i, int cur) {\n if (i == 4) return cur;\n if (ofB[i] == ofA[i]) return exchange(ofA, ofB, i + 1, cur);\n int min = 100;\n for (int j = i + 1; j < 4; ++j) {\n if (ofB[j] == ofA[i]) {\n ofB[j] = ofB[i];\n min = Math.min(exchange(ofA, ofB, i + 1, cur+1), min);\n if (min <= 2) return min; \n ofB[j] = ofA[i];\n }\n }\n return min;\n }\n}\n\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Works in Java, TLE in python, super simple solution.
works-in-java-tle-in-python-super-simple-f6l5
Intuition\nThe hint given after the contest was the intuiton.\n\n# Code\njava []\nimport java.util.*;\n\nclass Solution {\n public HashSet<Integer> get_possi
Mudit-B
NORMAL
2024-08-25T04:44:51.493118+00:00
2024-08-25T04:45:44.215672+00:00
24
false
# Intuition\nThe hint given after the contest was the intuiton.\n\n# Code\n```java []\nimport java.util.*;\n\nclass Solution {\n public HashSet<Integer> get_possible_integers(int num) {\n HashSet<Integer> possibleSwaps = new HashSet<>();\n // find out all the possible combination of swaps\n possibleSwaps.add(num);\n String numStr = String.format("%07d", num);\n \n for (int i = 0; i < 7; i++) {\n for (int j = i; j < 7; j++) {\n for (int k = 0; k < 7; k++) {\n for (int l = k; l < 7; l++) {\n // pad it with 0\'s to avoid index out of bounds\n char[] option = new char[7];\n Arrays.fill(option, \'0\');\n System.arraycopy(numStr.toCharArray(), 0, option, 7 - numStr.length(), numStr.length());\n \n // swap i, j and k, l \n // where i could be j and k could be l\n // so this considers atmost 2 swaps\n char temp1 = option[i];\n option[i] = option[j];\n option[j] = temp1;\n \n char temp2 = option[k];\n option[k] = option[l];\n option[l] = temp2;\n \n // convert option back to int\n possibleSwaps.add(Integer.parseInt(new String(option)));\n }\n }\n }\n }\n return possibleSwaps;\n }\n\n public int countPairs(int[] nums) {\n Map<Integer, Integer> pairCandidates = new HashMap<>();\n int pairCount = 0;\n for (int num : nums) {\n pairCount += pairCandidates.getOrDefault(num, 0);\n HashSet<Integer> possibleSwaps = get_possible_integers(num);\n for (int swap : possibleSwaps) {\n pairCandidates.put(swap, pairCandidates.getOrDefault(swap, 0) + 1);\n }\n }\n return pairCount;\n }\n}\n```\n```python []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n def get_possible_integers(num):\n possible_swaps = set()\n # find out all the possible combination of swaps\n possible_swaps.add(num)\n num_str = str(num)\n \n for i in range(7):\n for j in range(i, 7):\n for k in range(7):\n for l in range(k, 7):\n # pad it with 0\'s to avoid index out of bounds\n option = list(\'0\' * (7 - len(num_str)) + num_str)\n # swap i, j and k, l \n # where i could be j and k could be l\n # so this considers atmost 2 swaps\n option[i], option[j] = option[j], option[i]\n option[k], option[l] = option[l], option[k]\n # convert option back to int\n possible_swaps.add(int("".join(option)))\n return possible_swaps\n\n pair_candidates = defaultdict(int)\n pair_count = 0\n for num in nums:\n pair_count += pair_candidates[num]\n possible_swaps = get_possible_integers(num)\n for swap in possible_swaps:\n pair_candidates[swap] += 1\n \n return pair_count\n```
0
0
['Java', 'Python3']
0
count-almost-equal-pairs-ii
Fastest Solution in C++, Java, and Python
fastest-solution-in-c-java-and-python-by-l5l6
Credit:\nSpecial thanks to bilyhurington for his c++ solution which derives the other forms.\n\n# Code\nc++ []\nclass Solution {\npublic:\n const int L=7;\n
20250309.retired_account
NORMAL
2024-08-25T04:40:44.867091+00:00
2024-08-25T04:40:44.867116+00:00
115
false
# Credit:\nSpecial thanks to [bilyhurington](https://leetcode.com/u/bilyhurington) for his c++ solution which derives the other forms.\n\n# Code\n```c++ []\nclass Solution {\npublic:\n const int L=7;\n int countPairs(vector<int>& nums) {\n int n=nums.size();\n unordered_map<string,int> mp,id;\n int ans=0;\n for(int i=1;i<=n;i++){\n int x=nums[i-1];\n string s;\n for(int j=0;j<L;j++){\n s+=(x%10)+\'0\';\n x/=10;\n }\n ans+=mp[s];\n mp[s]++;\n id[s]=i;\n for(int p=0;p<L;p++){\n for(int q=p+1;q<L;q++){\n if(s[p]==s[q]) continue;\n swap(s[p],s[q]);\n if(id[s]<i){\n id[s]=i;\n mp[s]++;\n }\n for(int r=p;r<L;r++){\n for(int t=r+1;t<L;t++){\n if(s[r]==s[t]) continue;\n swap(s[r],s[t]);\n if(id[s]<i){\n id[s]=i;\n mp[s]++;\n }\n swap(s[r],s[t]);\n }\n }\n swap(s[p],s[q]);\n }\n }\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n private static final int L = 7;\n\n public int countPairs(int[] nums) {\n int n = nums.length;\n Map<String, Integer> mp = new HashMap<>();\n Map<String, Integer> id = new HashMap<>();\n int ans = 0;\n\n for (int i = 1; i <= n; i++) {\n int x = nums[i - 1];\n StringBuilder sb = new StringBuilder();\n for (int j = 0; j < L; j++) {\n sb.append((char) (x % 10 + \'0\'));\n x /= 10;\n }\n String s = sb.toString();\n ans += mp.getOrDefault(s, 0);\n mp.put(s, mp.getOrDefault(s, 0) + 1);\n id.put(s, i);\n\n char[] chars = s.toCharArray();\n for (int p = 0; p < L; p++) {\n for (int q = p + 1; q < L; q++) {\n if (chars[p] == chars[q]) continue;\n swap(chars, p, q);\n s = new String(chars);\n if (id.getOrDefault(s, 0) < i) {\n id.put(s, i);\n mp.put(s, mp.getOrDefault(s, 0) + 1);\n }\n for (int r = p; r < L; r++) {\n for (int t = r + 1; t < L; t++) {\n if (chars[r] == chars[t]) continue;\n swap(chars, r, t);\n s = new String(chars);\n if (id.getOrDefault(s, 0) < i) {\n id.put(s, i);\n mp.put(s, mp.getOrDefault(s, 0) + 1);\n }\n swap(chars, r, t);\n }\n }\n swap(chars, p, q);\n }\n }\n }\n return ans;\n }\n\n private void swap(char[] array, int i, int j) {\n char temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n}\n```\n```python3 []\nclass Solution:\n def countPairs(self, nums):\n maxL = 7\n n = len(nums)\n mp = defaultdict(int)\n ids = {}\n ans = 0\n\n for i in range(1, n + 1):\n x = nums[i - 1]\n s = \'\'\n # convert x to a string s and pad with zeros\n # using str(x).zfill(maxL) also works here\n for _ in range(maxL):\n s += chr((x % 10) + ord(\'0\'))\n x //= 10\n\n ans += mp[s] # efficiently count the matches.\n mp[s] += 1\n ids[s] = i\n\n s = list(s)\n\n for p in range(maxL):\n for q in range(p + 1, maxL):\n if s[p] == s[q]:\n continue\n s[p], s[q] = s[q], s[p]\n s_str = \'\'.join(s)\n if ids.get(s_str, 0) < i:\n ids[s_str] = i\n mp[s_str] += 1\n for r in range(p, maxL):\n for t in range(r + 1, maxL):\n if s[r] == s[t]:\n continue\n s[r], s[t] = s[t], s[r]\n s_str = \'\'.join(s)\n if ids.get(s_str, 0) < i:\n ids[s_str] = i\n mp[s_str] += 1\n s[r], s[t] = s[t], s[r]\n s[p], s[q] = s[q], s[p]\n \n return ans\n```
0
0
['Python', 'C++', 'Java', 'Python3']
0
count-almost-equal-pairs-ii
Simple Brute force Solution
simple-brute-force-solution-by-ankuraj_2-cc6z
Code\ncpp []\nclass Solution {\npublic:\n unordered_set<int> f(int a) {\n unordered_set<int> st;\n string s=to_string(a);\n for(int i=0;
ankuraj_27
NORMAL
2024-08-25T04:35:57.660293+00:00
2024-08-25T04:35:57.660342+00:00
60
false
# Code\n```cpp []\nclass Solution {\npublic:\n unordered_set<int> f(int a) {\n unordered_set<int> st;\n string s=to_string(a);\n for(int i=0;i<s.size();i++) {\n for(int j=i+1;j<s.size();j++) {\n string temp=s;\n swap(temp[i],temp[j]);\n st.insert(stoi(temp));\n for(int k1=0;k1<s.size();k1++) {\n for(int k2=k1+1;k2<s.size();k2++) {\n string tmp=temp;\n swap(tmp[k1],tmp[k2]);\n st.insert(stoi(tmp));\n }\n }\n }\n }\n return st;\n }\n int countPairs(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n map<int,int> mp;\n int cnt=0,n=nums.size();\n for(int i=0;i<n;i++) {\n unordered_set<int> st=f(nums[i]);\n for(auto it:st) {\n cnt+=mp[it];\n }\n mp[nums[i]]++;\n }\n for(auto it:mp) {\n if(it.first/10==0) {\n cnt+=it.second*(it.second-1)/2;\n }\n }\n return cnt;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Java || 100% Beats
java-100-beats-by-vilaparthibhaskar-st0z
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
vilaparthibhaskar
NORMAL
2024-08-25T04:18:55.839731+00:00
2024-08-25T04:18:55.839750+00:00
29
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nimport java.util.*;\n\npublic class Solution {\n public int countPairs(int[] nums) {\n Map<Integer, Integer> countMap = new HashMap<>();\n for (int num : nums) {\n countMap.put(num, countMap.getOrDefault(num, 0) + 1);\n }\n\n List<Integer> uniqueNums = new ArrayList<>(countMap.keySet());\n Collections.sort(uniqueNums);\n\n long ans = 0;\n int n = uniqueNums.size();\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n String x = Integer.toString(uniqueNums.get(i));\n String y = Integer.toString(uniqueNums.get(j));\n if (helper(x, y)) {\n ans += (long) countMap.get(uniqueNums.get(j)) * countMap.get(uniqueNums.get(i));\n }\n }\n }\n\n for (int freq : countMap.values()) {\n ans += (long) freq * (freq - 1) / 2;\n }\n\n return (int) ans;\n }\n\n private boolean helper(String x, String y) {\n int count = 0;\n List<Character> a = new ArrayList<>(), b = new ArrayList<>();\n int l1 = x.length(), l2 = y.length();\n\n for (int i = -1; i >= -Math.max(l1, l2) - 1; --i) {\n char f = (i >= -l1) ? x.charAt(l1 + i) : \'0\';\n char s = (i >= -l2) ? y.charAt(l2 + i) : \'0\';\n\n if (f != s) {\n a.add(f);\n b.add(s);\n count++;\n }\n\n if (count > 4) return false;\n }\n\n Map<Character, Integer> countA = new HashMap<>(), countB = new HashMap<>();\n for (char c : a) countA.put(c, countA.getOrDefault(c, 0) + 1);\n for (char c : b) countB.put(c, countB.getOrDefault(c, 0) + 1);\n\n if (!countA.equals(countB)) return false;\n if (count == 2 || count == 3) return true;\n if (count == 4) {\n char req = b.get(0);\n for (int i = 1; i < 4; ++i) {\n if (a.get(i) == req) {\n if (a.get(0) == b.get(i)) return true;\n }\n }\n }\n return false;\n }\n}\n\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Optimizing the brute force O(n*n) approach
optimizing-the-brute-force-onn-approach-xgkz8
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nWorking around the time
Amit_Aswal
NORMAL
2024-08-25T04:18:11.602084+00:00
2024-08-25T04:18:11.602112+00:00
36
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWorking around the time limit by sorting the array and using the previous result \n\n# Complexity\n- Time complexity:\n- O(N*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countPairs(int[] nums) {\n // HashMap<Integer,HashMap<Integer,Integer>> map = new HashMap<>();\n Arrays.sort(nums);\n int count = 0;\n // for(int i =0;i<nums.length;i++){\n // map.put(nums[i],new HashMap<Integer,Integer>());\n // }\n int prev = 0;\n for(int i =0;i<nums.length;i++){\n if(i>0 && nums[i] == nums[i-1]){\n count+= prev -1;\n prev--;\n continue;\n }\n prev = 0;\n int temp = 0;\n for(int j= i+1;j<nums.length;j++){\n if(j>i+1 && nums[j] == nums[j-1]){\n count+=temp;\n prev+=temp;\n }\n else if(almostEqual(nums[i],nums[j])){\n count++;\n prev++;\n temp = 1;\n }\n else{\n temp = 0;\n }\n }\n }\n return count;\n }\n public boolean almostEqual(int a,int b){\n if(a==b){\n return true;\n }\n StringBuilder s1 = new StringBuilder(""+a);\n StringBuilder s2 = new StringBuilder(""+b);\n if(s1.length()<s2.length()){\n while(s1.length()<s2.length()){\n s1.insert(0,\'0\');\n }\n }\n\n int[] freq = new int[10];\n for(int i =0;i<s1.length();i++){\n freq[s1.charAt(i)%10]++;\n }\n for(int i =0;i<s2.length();i++){\n if(--freq[s2.charAt(i)%10] < 0){\n return false;\n }\n }\n\n\n\n int count =0;\n int[] arr =new int[4];\n for(int i =0;i<s1.length();i++){\n if(s1.charAt(i)!=s2.charAt(i)){\n if(count == 4){\n return false;\n }\n arr[count] = i;\n count++;\n }\n }\n if(count<=3){\n return true;\n }\n if(count == 4){\n char c = s1.charAt(arr[0]);\n for(int i=1;i<4;i++){\n if(c == s2.charAt(arr[i]) && s1.charAt(arr[i]) == s2.charAt(arr[0])){\n // System.out.println(s2);\n return true;\n }\n }\n }\n return false;\n }\n // 1023 1023\n // 2130 2310\n // 3282 \n // 2823\n}\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Easy Map Solution
easy-map-solution-by-kvivekcodes-7sll
Starting from beginning, use one and two swaps and then see if rearranged numbers are present or not.\nTo avoid overcounting just maintain of count of numbers o
kvivekcodes
NORMAL
2024-08-25T04:15:47.531787+00:00
2024-08-25T04:15:47.531813+00:00
33
false
Starting from beginning, use one and two swaps and then see if rearranged numbers are present or not.\nTo avoid overcounting just maintain of count of numbers of ending numbers only.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n\n int ans = 0;\n map<int, int> mp; // numbers that are present\n for(auto it: nums) mp[it]++;\n for(int i = 0; i < n; i++){\n mp[nums[i]]--; // decrease the count of current number as we are comparing next numbers.\n ans += mp[nums[i]]; // using 0 operation\n string s = to_string(nums[i]);\n reverse(s.begin(), s.end());\n while(s.size() < 7) s += \'0\';\n set<int> vals; // all the numbers that can be made by rearranging\n\n // one operation\n for(int k = 0; k < 7; k++){\n for(int j = k+1; j < 7; j++){\n if(s[k] == s[j]) continue;\n swap(s[k], s[j]);\n reverse(s.begin(), s.end());\n int cnt = stoi(s);\n reverse(s.begin(), s.end());\n if(mp.find(cnt) != mp.end()) vals.insert(cnt);\n swap(s[k], s[j]);\n }\n }\n\n // two operation\n for(int p = 0; p < 7; p++){\n for(int j = p+1; j < 7; j++){\n if (s[p] == s[j]) continue;\n swap(s[p], s[j]);\n\n for (int k = 0; k < 7; k++) {\n for (int l = k + 1; l < 7; l++) {\n if (s[k] == s[l] || (k == p && l == j)) continue;\n swap(s[k], s[l]); \n reverse(s.begin(), s.end());\n int cnt = stoi(s); \n reverse(s.begin(), s.end());\n if (mp.find(cnt) != mp.end()) vals.insert(cnt);\n swap(s[k], s[l]); \n }\n }\n\n swap(s[p], s[j]);\n }\n }\n for(auto it: vals) ans += mp[it];\n }\n\n return ans;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Short solution [Python3]
short-solution-python3-by-timetoai-xrmv
Approach\nProblem is as simple as count equal numbers pairs, just do this with permutations.\n\ngo function generates all possible permutations within 2 steps.\
timetoai
NORMAL
2024-08-25T04:09:29.714078+00:00
2024-08-25T04:09:29.714108+00:00
27
false
# Approach\nProblem is as simple as count equal numbers pairs, just do this with permutations.\n\n`go` function generates all possible permutations within 2 steps.\n\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n @cache\n def go(num):\n cur = [list(str(num))]\n s = set()\n s.add(\'\'.join(cur[0]))\n for _ in range(2):\n nxt = []\n for n in cur:\n for i in range(len(n)):\n for j in range(i + 1, len(n)):\n nn = n.copy()\n nn[i], nn[j] = nn[j], nn[i]\n snn = \'\'.join(nn).lstrip(\'0\')\n if snn not in s:\n s.add(snn)\n nxt.append(nn)\n cur = nxt\n return s\n \n ret = 0\n cnt = defaultdict(int)\n for num in sorted(nums, reverse=True):\n ret += cnt[str(num)]\n for sub in go(num):\n cnt[sub] += 1\n return ret\n \n```
0
0
['Python3']
0
count-almost-equal-pairs-ii
Beats 100% java users
beats-100-java-users-by-aditya_vish-k13z
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
aditya_vish
NORMAL
2024-08-25T04:07:16.423153+00:00
2024-08-25T04:07:16.423183+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nimport java.util.*;\n\nclass Solution {\n String makeDigit(int num, int digits) {\n String numStr = Integer.toString(num);\n\n // If the string length is less than the desired size, prepend zeros\n if (numStr.length() < digits) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < digits - numStr.length(); i++) {\n sb.append(\'0\');\n }\n sb.append(numStr);\n numStr = sb.toString();\n }\n\n return numStr;\n }\n\n Set<String> makeSwapChanges(int num, int digits) {\n String s = makeDigit(num, digits);\n Set<String> poss = new HashSet<>();\n poss.add(s);\n\n char[] charArray = s.toCharArray();\n for (int i = 0; i < digits; ++i) {\n for (int j = i + 1; j < digits; ++j) {\n if (charArray[i] != charArray[j]) {\n swap(charArray, i, j);\n poss.add(new String(charArray));\n for (int i1 = 0; i1 < digits; ++i1) {\n for (int j1 = 0; j1 < digits; ++j1) {\n if (i == i1 && j == j1) continue;\n\n if (charArray[i1] != charArray[j1]) {\n swap(charArray, i1, j1);\n poss.add(new String(charArray));\n swap(charArray, j1, i1);\n }\n }\n }\n swap(charArray, i, j);\n }\n }\n }\n return poss;\n }\n\n private void swap(char[] array, int i, int j) {\n char temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n\n public int countPairs(int[] nums) {\n int n = nums.length;\n\n int mx = 0;\n for (int num : nums) mx = Math.max(mx, num);\n\n int digits = Integer.toString(mx).length();\n\n Map<String, Integer> mp = new HashMap<>();\n mp.put(makeDigit(nums[0], digits), mp.getOrDefault(makeDigit(nums[0], digits), 0) + 1);\n int ans = 0;\n for (int i = 1; i < n; ++i) {\n for (String s : makeSwapChanges(nums[i], digits)) {\n ans += mp.getOrDefault(s, 0);\n }\n\n mp.put(makeDigit(nums[i], digits), mp.getOrDefault(makeDigit(nums[i], digits), 0) + 1);\n }\n\n return ans;\n }\n}\n\n\n```
0
0
['Java']
0
count-almost-equal-pairs-ii
Easy || C++ || Brute force Code
easy-c-brute-force-code-by-raven572-fir5
Intuition\n Describe your first thoughts on how to solve this problem. \nSimple brute solution using set and map\n\n# Approach\n Describe your approach to solvi
raven572
NORMAL
2024-08-25T04:04:38.434491+00:00
2024-08-25T04:04:38.434525+00:00
180
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimple brute solution using set and map\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n set<int> f(int n){\n string num = to_string(n);\n set<int> st;\n st.insert(n);\n for(int i=0;i<num.size();i++){\n for(int j=i+1;j<num.size();j++){\n swap(num[i],num[j]);\n int number = stoi(num);\n st.insert(number);\n for(int x=0;x<num.size();x++){\n for(int y=x+1;y<num.size();y++){\n swap(num[x],num[y]);\n int num2 = stoi(num);\n st.insert(num2);\n swap(num[x],num[y]);\n }\n }\n swap(num[i],num[j]);\n }\n }\n return st;\n }\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n vector<int> hsh(n,0);\n sort(nums.begin(),nums.end());\n int ct = 0;\n map<int,int> mp;\n for(int i=0;i<n;i++){\n set<int> st = f(nums[i]);\n for(auto it:st){\n if(mp.find(it) != mp.end());\n ct += mp[it];\n }\n mp[nums[i]]++;\n }\n return ct;\n }\n};\n```
0
0
['C++']
0
count-almost-equal-pairs-ii
Python Hard
python-hard-by-lucasschnee-is13
python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n N = len(nums)\n \n lookup = defaultdict(int)\n \n
lucasschnee
NORMAL
2024-08-25T04:04:12.504704+00:00
2024-08-25T04:04:12.504729+00:00
39
false
```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n N = len(nums)\n \n lookup = defaultdict(int)\n \n \n \n mx = 0\n \n total = 0\n \n for i in range(N):\n nums[i] = str(nums[i])\n mx = max(mx, len(nums[i]))\n \n \n for i in range(N):\n while len(nums[i]) < mx:\n nums[i] = "0" + nums[i]\n \n lookup[nums[i]] += 1\n \n \n \n arr = []\n \n for i in range(N):\n if lookup[nums[i]] != 0:\n \n A = [0] * 10\n for x in nums[i]:\n A[int(x)] += 1\n \n arr.append((tuple(A), nums[i], lookup[nums[i]]))\n lookup[nums[i]] = 0\n \n \n d = defaultdict(list)\n \n\n \n for u, v, l in arr:\n d[u].append((v, l))\n \n \n \n \n N = len(arr)\n \n \n # print(arr)\n \n for i in range(N):\n if arr[i][2] > 1:\n total += math.comb(arr[i][2], 2)\n \n \n# print(total)\n \n# print(d)\n\n \n for x in list(d.keys()):\n # print(x)\n # print(x)\n \n \n B = d[x]\n N = len(B)\n # print(B)\n \n for i in range(N):\n for j in range(i + 1, N):\n # print(arr[i][0], arr[j][0])\n\n\n\n pairs = []\n for x, y in zip(B[i][0], B[j][0]):\n if x != y:\n pairs.append([x, y])\n \n # print(pairs)\n # print(arr)\n\n\n if not pairs:\n total += (B[i][1] * B[j][1])\n continue\n \n if len(pairs) == 1:\n total += (B[i][1] * B[j][1])\n continue\n \n\n if len(pairs) == 2:\n # print(total)\n total += (B[i][1] * B[j][1])\n # print(total)\n continue\n\n if len(pairs) > 4:\n continue\n\n\n\n if len(pairs) == 3:\n total += (B[i][1] * B[j][1])\n continue\n\n\n\n flag = True\n\n for p in pairs:\n if p[::-1] not in pairs:\n flag = False\n\n\n if flag:\n total += (B[i][1] * B[j][1])\n \n \n \n return total\n\n\n```
0
0
['Python3']
0
count-almost-equal-pairs-ii
Counting Almost Equal Pairs with Double Swap in a List | coderkb
counting-almost-equal-pairs-with-double-lw230
Intuition\nTo count pairs of integers in an array that become equal when two digits are swapped at most twice, we can generate all possible numbers by performin
coderkb
NORMAL
2024-08-25T04:02:32.279881+00:00
2024-08-25T04:02:32.279906+00:00
213
false
## Intuition\nTo count pairs of integers in an array that become equal when two digits are swapped at most twice, we can generate all possible numbers by performing up to two swaps on each number\'s digits. We then check how many of these generated numbers have already been seen in the array.\n\n## Approach\n1. **Digit Standardization:**\n - Convert each integer in the array to a standardized string format with leading zeros to ensure consistent digit length.\n\n2. **Generate Possible Numbers:**\n - For each number, generate all possible numbers that can be obtained by performing up to two swaps on its digits.\n - Use a `set` to store unique possibilities for each number.\n\n3. **Counting Valid Pairs:**\n - Traverse the array, and for each number, check if any of its possible swapped forms have been seen before using a hash map.\n - If so, increment the count by the frequency of the matched form.\n - Finally, update the hash map with the current number\'s standardized form.\n\n## Complexity\n- **Time complexity:** $$O(n \\times d^4)$$, where `n` is the number of integers in the array and `d` is the number of digits in the largest integer. The complexity is due to the nested loops for generating all possible swap combinations.\n- **Space complexity:** $$O(n \\times d^2)$$, where `n` is the number of integers, and `d^2` accounts for the storage of possible swaps for each number.\n\n## Code\n```cpp\nclass Solution {\n string makeDigit(int num, int digits) {\n string numStr = to_string(num);\n \n // If the string length is less than the desired size, prepend zeros\n if (numStr.length() < digits) {\n numStr.insert(numStr.begin(), digits - numStr.length(), \'0\');\n }\n \n return numStr;\n }\n\n unordered_set<string> makeSwapChanges(int num, int digits) {\n string s = makeDigit(num, digits);\n unordered_set<string> poss;\n poss.insert(s);\n \n for(int i = 0; i < digits; ++i) {\n for(int j = i + 1; j < digits; ++j) {\n if(s[i] != s[j]) {\n swap(s[i], s[j]);\n poss.insert(s);\n for(int i1 = 0; i1 < digits; ++i1) {\n for(int j1 = 0; j1 < digits; ++j1) {\n if(i == i1 && j == j1) continue;\n\n if(s[i1] != s[j1]) {\n swap(s[i1], s[j1]);\n poss.insert(s);\n swap(s[j1], s[i1]);\n }\n }\n }\n swap(s[i], s[j]);\n }\n }\n }\n return poss;\n }\n\npublic:\n int countPairs(vector<int>& nums) {\n int n = nums.size();\n\n int mx = 0;\n for(int num : nums) mx = max(mx, num);\n\n int digits = to_string(mx).size();\n\n unordered_map<string, int> mp;\n mp[makeDigit(nums[0], digits)]++;\n int ans = 0;\n for(int i = 1; i < n; ++i) {\n for(const auto& s : makeSwapChanges(nums[i], digits)) {\n if(mp.find(s) != mp.end()) {\n ans += mp[s];\n }\n }\n\n mp[makeDigit(nums[i], digits)]++;\n }\n\n return ans;\n }\n};\n```\n\nThis solution effectively handles counting "almost equal" pairs by leveraging digit manipulation and hashing, ensuring that the problem is tackled within acceptable time limits for the given constraints.
0
0
['C++']
0
count-almost-equal-pairs-ii
Just Brute Force in 29 lines
just-brute-force-in-29-lines-by-explosiv-u8yf
\n# Code\npython3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n result = 0\n cc = collections.Counter()\n for nu
ExplosiveBattery
NORMAL
2024-08-25T04:02:27.126666+00:00
2024-08-25T04:04:07.993631+00:00
274
false
\n# Code\n```python3 []\nclass Solution:\n def countPairs(self, nums: List[int]) -> int:\n result = 0\n cc = collections.Counter()\n for num in nums:\n result += cc[num]\n\n # change\n num_str = str(num)\n num_str = (7 - len(num_str)) * \'0\' + num_str\n\n s = set()\n s.add(num)\n for i1, j1 in itertools.combinations(range(len(num_str)), 2):\n for i2, j2 in itertools.combinations(range(len(num_str)), 2):\n tmp = list(num_str)\n tmp[i1], tmp[j1] = tmp[j1], tmp[i1]\n new_num = int(\'\'.join(tmp))\n if new_num not in s and new_num in cc:\n result += cc[new_num]\n s.add(new_num)\n \n tmp[i2], tmp[j2] = tmp[j2], tmp[i2]\n new_num = int(\'\'.join(tmp))\n if new_num not in s and new_num in cc:\n result += cc[new_num]\n s.add(new_num)\n cc[num] += 1\n return result\n```
0
0
['Python3']
1