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
permutation-sequence
{{ Swift }} 88% Beat ((Factorial Trix)) [[Trixy Hobbits]] {{ M.A.T.H.L.O.L. }}
swift-88-beat-factorial-trix-trixy-hobbi-io01
\nclass Solution {\n func getPermutation(_ n: Int, _ k: Int) -> String {\n \n var fac = [Int](repeating: 1, count: n + 1)\n for i in 1..
nraptis
NORMAL
2019-06-11T05:20:54.815533+00:00
2019-06-11T05:20:54.815568+00:00
222
false
```\nclass Solution {\n func getPermutation(_ n: Int, _ k: Int) -> String {\n \n var fac = [Int](repeating: 1, count: n + 1)\n for i in 1..<(n+1) { fac[i] = fac[i - 1] * i }\n fac.reverse()\n \n var k = k - 1\n \n var list = [Int](repeating: 0, count: n)\n for i in 1..<(n + 1) { list[i - 1] = i }\n \n var res = [Int]()\n \n for i in 1..<(n + 1) {\n var index = k / fac[i]\n res.append(list[index])\n list.remove(at: index) \n k -= fac[i] * index\n }\n \n return res.compactMap { String($0) }.joined()\n }\n}\n```\n\nThis is the same concept as previous solutions. \n\nIt is all stemmed from the fact that there are N! permutations for 1...N
4
0
[]
0
permutation-sequence
[[ C++ ]] 100% Beat ((Drooling Slackers + Community College Burnouts => Copy + Paste)) [[Awesome]]
c-100-beat-drooling-slackers-community-c-kvrq
\nclass Solution {\npublic:\n \n string getPermutation(int n, int k) {\n \n int aFac[n + 1];\n \n aFac[0] = 1;\n \n
nraptis
NORMAL
2019-06-11T04:39:38.944980+00:00
2019-06-11T04:39:38.945019+00:00
246
false
```\nclass Solution {\npublic:\n \n string getPermutation(int n, int k) {\n \n int aFac[n + 1];\n \n aFac[0] = 1;\n \n for (int i=1;i<=n;i++) {\n aFac[i] = i * aFac[i - 1];\n }\n \n char aList[n + 1];\n aList[n] = 0;\n int aListCount = n;\n \n char aRes[n + 1];\n aRes[n] = 0;\n int aResCount = 0;\n \n for (int i=1;i<=n;i++) {\n aList[i - 1] = \'0\' + i;\n }\n \n k -= 1;\n \n for (int i=1;i<=n;i++) {\n \n int aIndex = k / aFac[n - i];\n \n aRes[aResCount++] = aList[aIndex];\n \n for (int j=aIndex+1;j<n;j++) {\n aList[j-1] = aList[j];\n }\n \n k -= aIndex * aFac[n - i]; \n }\n return string(aRes);\n \n }\n};\n```\n\nPermutations of ABCD\n\nA + Permutations(BCD)\nB + Permutations(ACD)\nC + Permutations(ABD)\nD + Permutations(ABC)\n\nPermutations of BCD\n\nB + Permutations(CD)\nC + Permutations(BD)\nD + Permutations(BC)\n\nThere are X! permutations in every X length subsequence. So just copy the solution from the other kid. This won\'t help you code any video game.\n\n\n\n\n
4
0
[]
0
permutation-sequence
java 1ms factorial solution with detailed explanation
java-1ms-factorial-solution-with-detaile-jva8
Apparently, there are n! different permutations for given n. Suppose m is the first element, then there are n - 1! permuations for the rest n - 1 numbers. The c
pangeneral
NORMAL
2019-04-20T12:29:52.211958+00:00
2019-04-20T12:29:52.212000+00:00
769
false
Apparently, there are ```n!``` different permutations for given ```n```. Suppose ```m``` is the first element, then there are ```n - 1!``` permuations for the rest ```n - 1``` numbers. The case is similar to the second element to the nth element. \n\nWith that in mind, we can calculate the ```kth``` permutation from the first element to ```nth``` element. \nAt first, we save ```1``` to ```n``` in a list ```num``` ascendently. \nThen we traverse from ```1``` to ```n```, the index of the ```ith``` element in ```num``` equals to ```k / (n - i)!``` and ```k``` is updated to ```k % (n - i)```. The picked element is then removed from the list.\nKeep traversing until ```k = 0```. Then we add the rest elements in ```num``` to the ```kth``` permutation.\n\nThis solution has two tricks:\n1. Use a list to save candidate elements\n2. Set k to k - 1 (synchronize index) can simplify the calculation\n\n```\npublic String getPermutation(int n, int k) {\n\tStringBuilder sb = new StringBuilder("");\n\tList<Integer> num = new ArrayList<Integer>();\n\tfor(int i = 1; i <= n; i++) // save candidate elements in a list\n\t\tnum.add(i);\n\tint factorial = 1;\n\tfor(int i = 1; i <= n - 1; i++)\n\t\tfactorial *= i;\n\tk = k - 1; // synchronize the index\n\tfor(int i = 1; i < n; i++) {\n\t\tif( k == 0 )\n\t\t\tbreak;\n\t\tint index = k / factorial;\n\t\tk %= factorial;\n\t\tfactorial /= (n - i);\n\t\tsb.append(num.get(index));\n\t\tnum.remove(index);\n\t}\n\tfor(int i = 0; i < num.size(); i++)\n\t\tsb.append(num.get(i));\n\treturn sb.toString();\n}\n```
4
0
['Java']
0
permutation-sequence
6ms Java Solution
6ms-java-solution-by-mraufc-wari
Let's say n = 5 and k = 40; Currently we have the following individual numbers: 1 2 3 4 5 Among n! = 120 permutations (n-1)! = 24 of them will begin with "1", t
mraufc
NORMAL
2018-11-07T15:57:30.190691+00:00
2018-11-07T15:57:30.190738+00:00
594
false
Let's say n = 5 and k = 40; Currently we have the following individual numbers: ``` 1 2 3 4 5 ``` Among **n!** = **120** permutations **(n-1)!** = **24** of them will begin with **"1"**, the next **24** of them will begin with **"2"**, the next **24** will begin with **"3"** and so on. In which case **40th** element will begin with **"2"**. Now the problem becomes among the following numbers, what is the 40 - 24 = **16th** permutation: ``` 1 3 4 5 ``` The length of this set is 4, so **(4-1)!** = **6** of them will begin with **"1"**, the next **6** will begin with **"3"** and the next **6** wil begin with **"4"**. In which case **16th** element will begin with a **"4"**. Now the problem is what is the 16 - 12 = **4th** permutation of the following set: ``` 1 3 5 ``` **2** of them will begin with a **"1"** and **3rd** and **4th** permutation will begin with a **"3"** and we need the **2nd** permutation from the remaining set which is: ``` 1 5 ``` **1st** permutation will begin with a **"1"** and **2nd** will begin with **"5"**. Overall result is: ``` 24351 ``` ```java class Solution { public String getPermutation(int n, int k) { int[] numbers = new int[n]; for (int i = 1; i <= n; i++) numbers[i-1] = i; return perm(numbers, k); } private String perm(int[] input, int k) { if (input.length == 0) return ""; int len = input.length - 1; int cnt = factorial(len); int pos = 0; while (k - cnt > 0) { k -= cnt; pos++; } String result = Integer.toString(input[pos]); int[] rem = new int[len]; int ix = 0; for (int i = 0; i <= len; i++) { if (i == pos) continue; rem[ix++] = input[i]; } result += perm(rem, k); return result; } private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } } ```
4
0
[]
1
permutation-sequence
🤩Easy Approach using back tracking 🚀 ❗
easy-approach-using-back-tracking-by-mut-rrgo
IntuitionWe solve this using a backtracking approachComplexity Time complexity: O(n!) Generating all permutations has a time complexity of O(n!). Since we stop
muthupalani
NORMAL
2025-01-06T10:29:36.820515+00:00
2025-01-06T10:29:36.820515+00:00
520
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We solve this using a backtracking approach # Complexity - Time complexity: O(n!) <!-- Add your time complexity here, e.g. $$O(n)$$ --> Generating all permutations has a time complexity of O(n!). Since we stop once the k-th permutation is found, the worst-case time complexity is still approximately O(n!). - Space complexity: o(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> Space used for the recursion stack is O(n), where n is the number of elements. Additional space for the freq array is O(n). # Code ```python3 [] class Solution: def getPermutation(self, n: int, k: int) -> str: arr = [i for i in range(1, n + 1)] freq = [0] * n res = [] self.bpermute([], freq, k, arr, res) return ''.join(map(str, res)) def bpermute(self, temp: List[int], freq: List[int], k: int, arr: List[int], res: List[int]) -> int: if len(temp) == len(arr): k -= 1 if k == 0: res.extend(temp) return k for i in range(len(arr)): if not freq[i]: temp.append(arr[i]) freq[i] = 1 k = self.bpermute(temp, freq, k, arr, res) # Recurse if k == 0: # If the k-th permutation is found, stop further recursion return 0 # Backtrack temp.pop() freq[i] = 0 return k # Return k to continue the search ```
3
0
['Python3']
1
permutation-sequence
Easy C++ Solution
easy-c-solution-by-aradhya_070304-iyb0
Intuition\nThe problem leverages factorials to determine the position of digits in the kthpermutation by sequentially fixing each digit based on the remaining p
Aradhya_070304
NORMAL
2024-08-08T16:52:32.657417+00:00
2024-08-08T16:52:32.657454+00:00
786
false
# Intuition\nThe problem leverages factorials to determine the position of digits in the kthpermutation by sequentially fixing each digit based on the remaining permutations.\nBy reducing the problem size iteratively, we efficiently build the desired permutation without generating all permutations.\n\n# Approach\nCalculate the factorial to determine the block size for each digit\'s position and iteratively select and remove the appropriate digit from the list.\nUpdate k and adjust the factorial as you build the permutation string from left to right.\n\n# Complexity\n- Time complexity:\no(N^2)\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n int fact=1;\n vector<int>ans;\n for(int i=1;i<n;i++){\n fact=fact*i;\n ans.push_back(i);\n }\n ans.push_back(n);\n string sum="";\n k=k-1;\n while(true){\n sum+=to_string(ans[k/fact]);\n ans.erase(ans.begin()+k/fact);\n\n if(ans.size()==0)break;\n\n k=k%fact;\n fact=fact/ans.size();\n }\n return sum; \n }\n};\n```
3
0
['Math', 'Recursion', 'C++']
0
permutation-sequence
One Line Python Solution
one-line-python-solution-by-ntcqwq-r84m
Code\n\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n return \'\'.join(list(map(str, (list(permutations(list(range(1, n+1))))[k
zzzqwq
NORMAL
2024-07-08T17:30:45.375074+00:00
2024-07-08T17:30:45.375107+00:00
79
false
# Code\n```\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n return \'\'.join(list(map(str, (list(permutations(list(range(1, n+1))))[k-1]))))\n```
3
0
['Python3']
0
permutation-sequence
Using Next Permutation STL✨
using-next-permutation-stl-by-sajal2212-ksvf
Intuition\nThe problem involves finding the kth permutation of the numbers from 1 to n. The initial intuition seems to generate all permutations up to the kth p
Sajal2212
NORMAL
2024-03-03T13:47:24.457534+00:00
2024-03-03T13:47:24.457566+00:00
332
false
# Intuition\nThe problem involves finding the kth permutation of the numbers from 1 to n. The initial intuition seems to generate all permutations up to the kth permutation and return it.\n\n# Approach\nThe provided code generates all permutations of the numbers from 1 to n up to the kth permutation using the `next_permutation` function from the C++ Standard Library. It iteratively generates permutations until it reaches the kth permutation.\n\n# Complexity\n- Time complexity: \\(O(n \\cdot k \\cdot n!)\\) - Generating each permutation takes \\(O(n!)\\) time, and the loop iterates \\(k\\) times.\n- Space complexity: \\(O(n)\\) - Additional space is used for storing the generated permutation.\n\n# Code\n```cpp\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n int number = 0;\n // Generate a number containing digits from 1 to n\n for (int i = 1; i <= n; i++) {\n number = number * 10 + i;\n }\n string ans = to_string(number);\n int i = 1;\n // Generate permutations until the kth permutation is reached\n while (i != k) {\n next_permutation(ans.begin(), ans.end());\n i++;\n }\n return ans;\n }\n};\n```\n\nThis code generates all permutations up to the kth permutation and returns it. However, this approach is not efficient, especially for large values of n and k, as it generates and discards many permutations. It can be optimized to directly calculate the kth permutation without generating all permutations.
3
0
['C++']
2
permutation-sequence
C++ | Beats 100%
c-beats-100-by-shubhamagrawal154-ao1t
Intuition\n\nIdea is to calculate each value of the permutation by dividing the complete range into sub-ranges. We will create an array for storing indices of t
shubhamagrawal154
NORMAL
2023-12-30T11:57:18.359465+00:00
2023-12-30T11:57:18.359498+00:00
461
false
# Intuition\n\nIdea is to calculate each value of the permutation by dividing the complete range into sub-ranges. We will create an array for storing indices of the sub-range and these indices will be used to get the final result.\n\n## ***Look below for illustration:***\n\nLet\'s take an example where `n = 4` and `k = 9`\n\nstep-1) calculate factorial of n, this will give the complete range\n```\nHere: 4! = 24\n```\n\nstep-2) divide the range into `n` sub-ranges\n```\nHere: 24/4 = 6; hence:\n```\n```\n1 => 1 -> 6\n2 => 7 -> 12\n3 => 13 -> 18\n4 => 19 -> 24\n```\n\nstep-3) Check which sub-range includes `k`. Here `k = 9` lies in `7->12` and it\'s index is `2`. Hence we add `2` in the final result. Also, remove `2` from the index vector.\n```\nresult: 2 _ _ _\n```\n\nstep-4) Steps `2` and `3` will be repeated until we get the desired result. Here, take the sub-range which will now be new range and sub-ranges will be calculated based on number of elements left in the index vector.\n```\n1 => 7 -> 8\n3 => 9 -> 10\n4 => 11 -> 12\n```\n\nstep-5) Since `9 -> 10` has index `3`, we add `3` in the final result.\n```\nresult: 2 3 _ _\n```\n\nstep-6) New sub-ranges would be as follows:\n```\n1 => 9\n4 => 10\n```\n\nstep-7) Since 9 has index 1, we add 1 in the final result.\n```\nresult: 2 3 1 _\n```\n\nstep-8) New sub-ranges would be as follows:\n```\n4 => 10\n```\n\nstep-9) Since only `4` is left, we add `4` in the final result.\n```\nresult: 2 3 1 4\n```\n\n# Approach\nWe will create `getSeq` function which will be called recursively. In this function, we will pass the value of `n`, `start` and `end` numbers. Based of these we will calulate sub-range based on following formula:\n\n```\nrange = end - start + 1;\ncurrrange = range/n;\n```\n\nNow we will run loop from `1 to n`, and add the index of the sub-range if the value of `k` lies in the sub-range. For this, we will calculate lower and higher values of the sub-range based on following formula:\n```\nlower = start + (i-1) * currrange;\nhigher = lower + currrange - 1;\n```\n\nFinal step would be to remove the `index` from indices array in which the sub-range lied and call the `getSeq` function and pass `lower` and `higher` values as `start` and `end` values; and pass `n-1` as we have removed one value from indices array.\n\n\n# Complexity\n- Time complexity: n*n\n\n\n- Space complexity: n\n\n\n# Code\n```\nclass Solution {\npublic:\n string s = "";\n int fact(int f){\n if(f==1) return 1;\n return f*fact(f-1);\n }\n void getSeq(int n, int k, vector<int>v, int start, int end){\n if(n==0) return;\n int range = end-start+1;\n int currrange = range/n;\n for(int i=1; i<=n; i++){\n int lower = start + (i-1)*currrange;\n int higher = lower + currrange - 1;\n if(k>=lower && k<=higher){\n s.append(to_string(v[i-1]));\n auto it = find(v.begin(), v.end(), v[i-1]);\n v.erase(it);\n getSeq(n-1, k, v, lower, higher);\n }\n }\n }\n string getPermutation(int n, int k) {\n vector<int> v;\n for(int i=0; i<n; i++){\n v.push_back(i+1);\n }\n int start = 1;\n int end = fact(n);\n getSeq(n,k,v, start, end);\n return s;\n }\n};\n```
3
0
['C++']
1
permutation-sequence
Python 10ms solution
python-10ms-solution-by-sirfurno-8z31
Intuition\nFor this problem, my first realization was that for each starting number there are (n-1)! possibilites. Eg:\n\nn=4\nfor the starting number 1 the pos
sirfurno
NORMAL
2023-09-18T21:36:13.132249+00:00
2023-09-18T21:36:13.132278+00:00
528
false
# Intuition\nFor this problem, my first realization was that for each starting number there are (n-1)! possibilites. Eg:\n\nn=4\nfor the starting number 1 the possiblities are:\n1,2,3,4\n1,2,4,3\n1,3,2,4\n1,3,4,2\n1,4,2,3\n1,4,3,2\nThere are 6 possibilities which is the same as 3!\nSo with this, we should be able to through each digit and to find the proper number permutation. \n\n# Approach\nSomething to realize is that you can you can find the starting number for the permutation by doing k/(n-1)!\nThis is because for each possible starting number 1-n, there are (n-1)! possibilities, so if we divide k by this, we will get the starting number. \n\nSo you keep doing this for each digit. We divide k by (n-1)!, then add the integer part. K will then become whatever the remainder is, because we are subtracting that many possiblities. \n\n\n# Code\n```\nclass Solution(object):\n def getPermutation(self, n, k):\n #For each starting number there are (n-1)! possiblities. So the trick is you can find which digit it is by \n #Doing k/(n-1)!, and you get the starting number that fits that range, so you keep doing taht untill you reach the answer\n if k==1:\n return "".join([str(a) for a in range(1,n+1)])\n ans=""\n possible=[a for a in range(1,n+1)]\n k-=1#Because arrays start at 0, and this k starts at 1\n while n>0:\n n-=1\n index,k=divmod(k,math.factorial(n))\n ans+=str(possible[index])\n possible.pop(index)\n return ans\n\n """\n :type n: int\n :type k: int\n :rtype: str\n """\n\n```
3
0
['Python']
1
permutation-sequence
C++ Solution || beates 100% || easy to understand
c-solution-beates-100-easy-to-understand-lrrn
\n# Code\n\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n int fact = 1;\n vector<int> nums;\n string ans = "";\n
harshil_sutariya
NORMAL
2023-09-12T03:02:03.868746+00:00
2023-09-12T03:02:20.043794+00:00
301
false
\n# Code\n```\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n int fact = 1;\n vector<int> nums;\n string ans = "";\n for(int i=1;i<n;i++){\n fact=fact*i;\n nums.push_back(i);\n }\n nums.push_back(n);\n k = k-1;\n while(true){\n ans = ans + to_string(nums[k/fact]);\n nums.erase(nums.begin() + k/fact);\n if(nums.size()==0){\n break;\n }\n k = k % fact;\n fact = fact / nums.size();\n }\n return ans;\n }\n};\n```
3
0
['Math', 'C++']
1
permutation-sequence
Most optimal solution without using recursion and backtracking with complete exaplanation
most-optimal-solution-without-using-recu-qryz
\n\n# Approach\nThe given solution aims to find the kth permutation sequence of numbers from 1 to n. It uses a mathematical approach to determine the digits of
priyanshu11_
NORMAL
2023-08-28T15:12:04.900128+00:00
2023-08-28T15:12:35.820119+00:00
799
false
\n\n# Approach\nThe given solution aims to find the kth permutation sequence of numbers from 1 to n. It uses a mathematical approach to determine the digits of the kth permutation by repeatedly calculating the factorial of (n-1), identifying the next digit in the permutation, and updating the remaining digits.\n\nHere\'s the explanation of the solution steps:\n\n1. Calculate the factorial of (n-1) to determine the count of permutations that can be formed with the remaining digits.\n2. Create a list called nums containing numbers from 1 to n.\n3. Adjust k to be 0-based (k = k - 1).\n4. Repeatedly find the next digit in the permutation by dividing k by the current factorial value. This indicates which digit from the remaining digits list should be added to the answer.\n5. Remove the selected digit from the nums list.\n6. Update k by taking the remainder after division by the current factorial value.\n7. Update the factorial value by dividing it by the size of the nums list.\n8. Repeat steps 4-7 until all digits are added to the answer.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n```C++ []\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n int fact = 1;\n vector<int> nums;\n \n for (int i = 1; i < n; i++) {\n fact = fact * i;\n nums.push_back(i);\n }\n nums.push_back(n);\n \n string ans = "";\n k = k - 1;\n \n while (true) {\n ans = ans + to_string(nums[k / fact]);\n nums.erase(nums.begin() + k / fact);\n \n if (nums.size() == 0) {\n break;\n }\n \n k = k % fact;\n fact = fact / nums.size();\n }\n \n return ans;\n }\n};\n\n```\n```JAVA []\nclass Solution {\n public String getPermutation(int n, int k) {\n int fact = 1;\n List<Integer> nums = new ArrayList<>();\n \n for (int i = 1; i < n; i++) {\n fact *= i;\n nums.add(i);\n }\n nums.add(n);\n \n StringBuilder ans = new StringBuilder();\n k--;\n \n while (true) {\n ans.append(nums.get(k / fact));\n nums.remove(k / fact);\n \n if (nums.isEmpty()) {\n break;\n }\n \n k %= fact;\n fact /= nums.size();\n }\n \n return ans.toString();\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n fact = 1\n nums = list(range(1, n + 1))\n \n for i in range(1, n):\n fact *= i\n \n ans = []\n k -= 1\n \n while True:\n ans.append(str(nums[k // fact]))\n nums.pop(k // fact)\n \n if not nums:\n break\n \n k %= fact\n fact //= len(nums)\n \n return \'\'.join(ans)\n**Bold**\n```\n\n
3
0
['Math', 'Python', 'C++', 'Java', 'Python3']
2
permutation-sequence
BEST SOLUTION POSSIBLE | WORLD RECORD | IQ 10000+
best-solution-possible-world-record-iq-1-8cy7
Intuition\nSolve more problems you will get the intuition. \n\n# Approach\nArey bindu, dekh agar n=5 hai toh agar mai kisi ek number from 1-5 ko first element b
NayakPenguin
NORMAL
2023-07-23T00:15:10.471133+00:00
2023-07-23T00:15:10.471178+00:00
44
false
# Intuition\nSolve more problems you will get the intuition. \n\n# Approach\nArey bindu, dekh agar n=5 hai toh agar mai kisi ek number from 1-5 ko first element banata hu toh 4! options hoga each ka. \n\nAgar k = 59 hai, then k = (24 + 24 + 11). \nThat means starting mai 3 ayega and uske ander permutions hoga further.\nWhi dekh le re thoda. \n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n string helper(int n, set<int> st, int k){\n // basecase\n if(n == st.size()){ return ""; }\n \n // transition\n int val = 1;\n for(int i = 1; i<n - st.size(); i++) val *= i;\n\n int pos = k/val + (k%val ? 1 : 0);\n \n string s;\n for(int i = 1; i<=n; i++){\n if(st.find(i) == st.end() && --pos == 0){\n st.insert(i);\n s = \'0\' + i;\n break;\n }\n }\n\n return s + helper(n, st, (k % val) ? (k % val) : val);\n }\n\n string getPermutation(int n, int k) {\n set<int> st;\n return helper(n, st, k);\n }\n};\n```
3
0
['Math', 'Recursion', 'C++']
0
permutation-sequence
Simple C++ Code
simple-c-code-by-abhradip_360-0wjp
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
abhradip_360
NORMAL
2023-05-05T16:59:45.227621+00:00
2023-05-05T16:59:45.227664+00:00
69
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```\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n vector<int>v(n), vv;\n for(int i=0;i<n;i++)\n v[i]=i+1;\n int p=0;\n do\n {\n p++;\n if(p==k)\n {\n for(auto it:v)\n vv.push_back(it);\n break;\n }\n }while(next_permutation(v.begin(),v.end()));\n string s="";\n \n for(auto it:vv)\n s+=to_string(it);\n return s;\n \n }\n};\n```
3
0
['C++']
0
permutation-sequence
java Solution beats 100% (sometimes 98%) non recursive
java-solution-beats-100-sometimes-98-non-o74a
Intuition\nIterative traversal and removal of elemnents from the bucket\n# Approach\nthe appraoch is based upon how u take benifit of factorial\n\n# Complexity\
rajAbhinav
NORMAL
2023-04-20T06:15:33.518564+00:00
2023-04-20T06:15:33.518602+00:00
1,387
false
# Intuition\nIterative traversal and removal of elemnents from the bucket\n# Approach\nthe appraoch is based upon how u take benifit of factorial\n\n# Complexity\n- Time complexity:\nO(N) beats 100%\n\n- Space complexity:\n beats 83%\n# Code\n```\nclass Solution {\n public String getPermutation(int n, int k) {\n List<Integer> lr = new ArrayList<>();\n int sum=1;\n for(int i=1;i<=n;i++) {lr.add(i);sum*=i;}\n StringBuilder sb = new StringBuilder();\n while(lr.size()!=0&&n>0)\n {\n //succesively decreasing the factorials value\n sum/=n--;\n //a considered case when a new row of element is going to start fr.eg if n=4 and k=12 then it is sitting at the max of getting \'2\' at first place i.e. 2431 after 3s line will take place\n if(k%sum==0){sb.append(lr.remove(k/(sum)-1)); for(int i=lr.size()-1;i>=0;i--) sb.append(lr.get(i)); return sb.toString();}\n // removing the element based on how the get considered by k\n sb.append(lr.remove(k/(sum)));\n\n k=k%sum;\n }\n return sb.toString();\n }\n}\n```
3
0
['Java']
1
permutation-sequence
Easy C++ solution
easy-c-solution-by-ddivyassingh-kczj
\n\n\n# Complexity\n- Time complexity:\nO(n^2) \n\n- Space complexity:\nO(n) \n\n# Code\n\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\
ddivyassingh
NORMAL
2023-03-21T11:52:33.617636+00:00
2023-03-21T11:52:33.617673+00:00
9
false
\n\n\n# Complexity\n- Time complexity:\nO(n^2) \n\n- Space complexity:\nO(n) \n\n# Code\n```\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n vector<int> nums;\n string ans="";\n k=k-1;\n int fact=1;\n for (int i=0 ; i<n; i++)\n {\n fact=fact*(i+1);\n nums.push_back(i+1);\n\n }\n fact=fact/n;\n while(true)\n {\n ans=ans+ to_string(nums[k/fact]);\n nums.erase(nums.begin()+k/fact);\n if(nums.size()==0)\n {\n break;\n }\n k=k%fact;\n fact=fact/nums.size();\n }\n return ans;\n }\n};\n```
3
0
['C++']
0
permutation-sequence
3ms || N*N || C++ || SHORT & SWEET CODE || ITERATIVE
3ms-nn-c-short-sweet-code-iterative-by-y-2a8y
\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n vector<int> v(n+1,false);\n vector<int> fact(n+1,1);\n for(int i =
yash___sharma_
NORMAL
2023-03-18T05:38:04.192075+00:00
2023-03-18T05:38:04.192106+00:00
4,820
false
```\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n vector<int> v(n+1,false);\n vector<int> fact(n+1,1);\n for(int i = 2; i <= n; i++){\n fact[i] = fact[i-1]*i;\n }\n string ans = "";\n k--;\n for(int i = 1; i <= n; i++){\n int x = k/fact[n-i],j,y=k;\n k -= x*fact[n-i];\n for(j = 1; j <= n; j++){\n if(v[j]==false&&x==0){\n break;\n }else if(v[j]==false){\n x--;\n }\n }\n if(j<=n)\n v[j] = true;\n ans = ans + to_string(j);\n }\n return ans;\n }\n};\n```
3
0
['Math', 'C', 'Iterator', 'C++']
0
permutation-sequence
Java || Beats 99.6% || 1ms runtime || Recursion
java-beats-996-1ms-runtime-recursion-by-uj1he
java []\nclass Solution {\n public String getPermutation(int n, int k) {\n int[] fact = new int[]{1,1,2,6,24,120,720,5040,40320};\n ArrayList<I
nishant7372
NORMAL
2023-03-17T16:48:35.132767+00:00
2023-03-17T16:48:35.132798+00:00
1,287
false
``` java []\nclass Solution {\n public String getPermutation(int n, int k) {\n int[] fact = new int[]{1,1,2,6,24,120,720,5040,40320};\n ArrayList<Integer> list = new ArrayList<>();\n for(int i=1;i<=n;i++){\n list.add(i);\n }\n return calc(fact,n,k-1,list,0)+"";\n }\n\n private int calc(int[] fact,int n,int k,ArrayList<Integer> list,int res){\n if(n==0)\n return res;\n res=res*10+list.remove(k/fact[n-1]);\n return calc(fact,n-1,k%fact[n-1],list,res);\n }\n}\n```
3
0
['Java']
0
permutation-sequence
1 Liner Code 😎 | Python
1-liner-code-python-by-arijitparia2002-i884
Intuition\n Describe your first thoughts on how to solve this problem. \n1. Using the Permutations to find all the possible permutations.\n2. Sorting in the asc
arijitparia2002
NORMAL
2023-03-02T23:21:08.459825+00:00
2023-03-02T23:21:08.459872+00:00
1,069
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Using the `Permutations` to find all the possible permutations.\n2. Sorting in the ascending order.\n3. Getting the `k-1` th value, which is a tuple\n4. Converting that tuple in string format.\n5. Returning the result.\n\n# Code\n```\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n return \'\'.join([str(i) for i in sorted(list(permutations([i for i in range(1, n+1)], n)))[k-1]])\n \n\n\n \n```
3
1
['Python', 'Python3']
1
permutation-sequence
Beats 99.7% 60. Permutation Sequence with step by step explanation
beats-997-60-permutation-sequence-with-s-66es
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nHere, we use a simple factorial approach. First, we calculate all the fac
Marlen09
NORMAL
2023-02-12T14:53:46.691149+00:00
2023-02-12T14:53:46.691205+00:00
952
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nHere, we use a simple factorial approach. First, we calculate all the factorials up to n, and use that to find the next number to add to the result. We start from the last factorial and keep adding numbers to the result, decrementing k and removing the selected number from the list. This continues until all numbers have been added to the result and k becomes 0. We return the result as a single string.\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```\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n nums = [i for i in range(1, n+1)] # list of numbers from 1 to n\n factorial = [1] * n # initialize factorial with n factorial of 1\n for i in range(1, n):\n factorial[i] = factorial[i-1] * i # calculate the factorials\n \n k -= 1 # decrement k by 1, since k is 1-indexed\n result = []\n for i in range(n-1, -1, -1):\n index = k // factorial[i] # calculate the index of the number to be picked\n result.append(str(nums[index])) # add the number to result\n nums.pop(index) # remove the number from the list\n k = k % factorial[i] # update k\n \n return \'\'.join(result) # join the result list into a single string and return\n\n```
3
0
['Python', 'Python3']
0
permutation-sequence
c++ || easy to understand || beats 100 percent || O(n^2)
c-easy-to-understand-beats-100-percent-o-d0ke
please upvote if you like the solution.\n# Code\n\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n string s = "" ;\n vector
strange6281
NORMAL
2023-01-10T05:04:45.465960+00:00
2023-04-23T18:16:22.860495+00:00
2,180
false
please upvote if you like the solution.\n# Code\n```\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n string s = "" ;\n vector<int>ds ;\n for(int i = 1 ; i <= n ; i++){\n ds.push_back(i) ;\n }\n int i = n ;\n while(k!= 0 && i >= 1){\n int r = fact(i-1) ;\n int c = check(r,k) ;\n s += to_string(ds[c]) ;\n ds.erase(ds.begin()+c) ;\n k = k -r*c ;\n i-- ;\n }\n return s ;\n }\n int check(int a ,int k){\n if(k%a == 0)return (k/a) - 1 ;\n return k/a ;\n }\n int fact(int n){\n if(n == 0)return 1 ;\n return n*fact(n-1) ;\n }\n};\n```
3
0
['C++']
2
permutation-sequence
C++ | 0ms | Recursive Solution
c-0ms-recursive-solution-by-sameer_22-abse
The basic idea is to decrease the search space. Now, what does this mean, Actually if we want to place a number at the first position then it will be having (n-
Sameer_22
NORMAL
2022-10-22T09:47:54.861186+00:00
2022-10-22T09:47:54.861233+00:00
470
false
The basic idea is to decrease the search space. Now, what does this mean, Actually if we want to place a number at the first position then it will be having (n-1)! ways to do it. So, let us take an example:\n\nn = 4 and k=9\n\nso, for suppose if we assume our answer will be having \'1\' at 1st position. Now let us write the possibilites:\n\n1 2 3 4\n1 2 4 3\n1 3 2 4\n1 3 4 2\n1 4 2 3\n1 4 3 2\n\nand our k value is 9 but the number of possible ways with 1 are only 6. So 1 can\'t be at first position.\n\nNow let us check for \'2\' but this time our k will be (9-6 = 3) [beacuse we will not again look into possiblilites of \'1\'].\n\nif we take 2 then 3-6<0, So here we can conclude that our answer will be having 2 at it\'s first position. And similarly we will be checking for remaining\n\n\n```\nvector<int>fact(10,1);\nclass Solution {\npublic: \n int Fact(int n){\n //Base\n if(n==1) return 1;\n return fact[n] = n*Fact(n-1);\n }\n void Helper(int n,int numbers,int k,string &res,unordered_map<int,bool>&ismarked){\n if(k < 0) return;\n int tk = k;\n for(int i=1;i<=n;i++){\n if(ismarked[i]) continue;\n if(tk-fact[numbers-1] <= 0){\n ismarked[i] = true;\n res+=to_string(i);\n Helper(n,numbers-1,tk,res,ismarked);\n }else{\n tk-=fact[numbers-1];\n }\n }\n }\n string getPermutation(int n, int k) {\n string res="";\n unordered_map<int,bool> ismarked;\n Fact(9);\n Helper(n,n,k,res,ismarked);\n return res;\n }\n};\n```
3
0
[]
0
permutation-sequence
Java optimized solution
java-optimized-solution-by-sharan79-bvqm
Approach : Brute Force\nWill Give TLE\n\nclass Solution {\n \n private void swap(char[] s , int i , int j){\n char temp = s[i];\n s[i] = s[j
Sharan79
NORMAL
2022-08-16T22:32:27.833050+00:00
2022-08-16T22:32:27.833083+00:00
633
false
### **Approach : Brute Force**\n**Will Give TLE**\n```\nclass Solution {\n \n private void swap(char[] s , int i , int j){\n char temp = s[i];\n s[i] = s[j];\n s[j] = temp;\n }\n \n private void solve(char[] s , int index , List<String> res){\n if(index == s.length){\n String str = new String(s);\n res.add(str);\n return;\n }\n for(int i = index; i<s.length ; i++){\n swap(s, i, index);\n solve(s, index+1, res);\n swap(s,i,index);\n }\n }\n \n public String getPermutation(int n, int k) {\n String s = "";\n ArrayList<String> res = new ArrayList<>();\n for(int i = 1; i <=n ; i++){\n s+=i;\n }\n solve(s.toCharArray(), 0 , res);\n Collections.sort(res);\n return res.get(k-1);\n }\n}\n\n//Time complexity: O(N! * N) +O(N! Log N!)\n//Space complexity: O(N) \n\n```\n\n\n### **Optimal solution**\n```\nclass Solution {\n public String getPermutation(int n, int k) {\n int fact = 1;\n List<Integer> numbers = new ArrayList<>();\n for(int i = 1; i<n ; i++){\n fact = fact * i;\n numbers.add(i);\n }\n numbers.add(n);\n String ans = "";\n k = k-1;\n while(true){\n ans = ans + "" + numbers.get(k/fact);\n numbers.remove(k/fact);\n if(numbers.size() == 0){\n break;\n }\n k = k % fact;\n fact = fact/numbers.size();\n }\n return ans;\n }\n}\n\n/*\nTime Complexity: O(N) * O(N) = O(N^2)\n\nReason: We are placing N numbers in N positions. This will take O(N) time. For every number, we are reducing the search space by removing the element already placed in the previous step. This takes another O(N) time.\n\nSpace Complexity: O(N) \n\nReason: We are storing the numbers in a data structure.\n*/\n```
3
0
['Backtracking', 'Recursion', 'Java']
0
permutation-sequence
Simple Mathematical Solution
simple-mathematical-solution-by-ryangray-thq3
\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n perm, fact = "", factorial(n)\n nums = [ i for i in range(1, n+1) ] #to
ryangrayson
NORMAL
2022-06-20T18:04:41.659106+00:00
2022-06-20T18:04:41.659155+00:00
345
false
```\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n perm, fact = "", factorial(n)\n nums = [ i for i in range(1, n+1) ] #to keep track of the options left\n for i in range(n, 0, -1):\n fact //= i\n cur_pos = (k-1) // fact #index of next number based on possibilities left\n perm += str( nums[cur_pos] )\n del nums[cur_pos] #get rid of the number we used\n k %= fact\n return perm\n```\nPlease upvote if you find it useful! :)
3
0
['Python']
0
permutation-sequence
CPP Recursion Easy Solution
cpp-recursion-easy-solution-by-abhishek2-hl7l
\tint count=0;\n string ans;\n void rightrotate(string& s, int i, int j){\n if(i==j)return;\n char temp=s[j];\n for(int k=j-1;k>=i;k-
abhishek23a
NORMAL
2022-06-07T10:00:22.573013+00:00
2022-06-07T10:00:22.573100+00:00
199
false
\tint count=0;\n string ans;\n void rightrotate(string& s, int i, int j){\n if(i==j)return;\n char temp=s[j];\n for(int k=j-1;k>=i;k--){\n s[k+1]=s[k];\n }\n s[i]=temp;\n }\n void leftrotate(string& s, int i, int j){\n if(i==j)return;\n char temp=s[i];\n for(int k=i;k<=j-1;k++){\n s[k]=s[k+1];\n }\n s[j]=temp;\n }\n void permute(string s, int i, int k){\n if(i==s.length()){\n count++;\n if(count==k){\n ans=s;\n return ;\n }\n }\n if(count>=k)return;\n for(int j=i; j<s.length();j++){\n rightrotate(s,i,j);\n permute(s,i+1,k);\n leftrotate(s,i,j);\n }\n }\n string getPermutation(int n, int k) {\n string str="123456789";\n string s=str.substr(0,n);\n cout<<s<<endl;\n permute(s,0,k);\n return ans;\n }
3
0
['Recursion']
0
largest-number-after-digit-swaps-by-parity
C++|| 0 ms || O(nlogn) || Easy to understand || Commented Explanation || Priority Queue
c-0-ms-onlogn-easy-to-understand-comment-9ki5
The simple idea is to store even and odd digits of the number num into 2 priority queues (max heap); and then iterate over every digit of num to look for places
gnipun05
NORMAL
2022-04-10T05:12:41.582604+00:00
2022-04-11T03:42:50.638649+00:00
8,890
false
The simple idea is to store even and odd digits of the number **num** into 2 priority queues (max heap); and then iterate over every digit of **num** to look for places having odd (or even) digits. And then placing the top of the respected queues over those postions.\n\nPlease do upvote if this solution helps.\n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<int> p; // priority queue to store odd digits in descending order\n priority_queue<int> q; // priority queue to store even digits in descending order\n string nums=to_string(num); // converting num to a string for easy access of the digits\n int n=nums.size(); // n stores the number of digits in num\n \n for(int i=0;i<n;i++){\n int digit=nums[i]-\'0\'; \n if((digit)%2) // if digit is odd, push it into priority queue p\n p.push(digit);\n else\n q.push(digit); // if digit is even, push it into priority queue q\n }\n \n int answer=0;\n for(int i=0; i<n; i++){\n answer=answer*10;\n if((nums[i]-\'0\')%2) // if the digit is odd, add the largest odd digit of p into the answer\n {answer+=p.top();p.pop();}\n else\n {answer+=q.top();q.pop();} // if the digit is even, add the largest even digit of q into the answer\n }\n return answer;\n }\n};\n```\nSpace: O(n)\nTime: O(nlogn)\n\nAny reccomendations are highly appreciated...
99
1
['C', 'Heap (Priority Queue)']
14
largest-number-after-digit-swaps-by-parity
Concise Java, 9 lines
concise-java-9-lines-by-climberig-l6g8
Look for a digit on the right that is bigger than the current digit and has the same parity, and swap them.\n(a[j] - a[i]) % 2 == 0 parity check (true if both a
climberig
NORMAL
2022-04-10T04:11:25.345652+00:00
2022-04-10T04:21:42.994353+00:00
5,949
false
Look for a digit on the right that is bigger than the current digit and has the same parity, and swap them.\n```(a[j] - a[i]) % 2 == 0``` parity check (true if both a[j] and a[i] are even or both are odd)\n```java\n public int largestInteger(int n){\n char[] a = String.valueOf(n).toCharArray();\n for(int i = 0; i < a.length; i++)\n for(int j = i + 1; j < a.length; j++)\n if(a[j] > a[i] && (a[j] - a[i]) % 2 == 0){\n char t = a[i];\n a[i] = a[j];\n a[j] = t;\n }\n return Integer.parseInt(new String(a));\n }
56
5
['Java']
19
largest-number-after-digit-swaps-by-parity
Python Solution using Sorting
python-solution-using-sorting-by-ancoder-wi2w
Since we need the largest number, what we want is basically to have the larger digits upfront and then the smaller ones. But we are given a parity condition tha
ancoderr
NORMAL
2022-04-10T04:02:10.466905+00:00
2022-04-10T04:34:17.165564+00:00
6,310
false
Since we need the largest number, what we want is basically to have the larger digits upfront and then the smaller ones. But we are given a parity condition that we need to comply to. We are allowed to swap odd digits with odd ones and even with even ones. So we simply maintain two arrays with odd and even digits. The we construct out answer by taking values from the odd or even arrays as per the parity of ith index. \n\n**STEPS**\n1. First make a array with the digits from nums.\n2. Then we traverse through the array and insert odd and even values into `odd` and `even` lists.\n3. We sort these `odd` and `even` lists.\n4. Then traverse from 0 to n, at each step we check for the parity at that index. For even parity we take the largest value from even array and for odd parity we take from odd array. **WE TAKE THE LARGEST VALUE AS A GREEDY CHOICE TO MAKE THE RESULTING NUMBER LARGER.**\n5. Return the result.\n\n**CODE**\n```\nclass Solution:\n def largestInteger(self, num: int):\n n = len(str(num))\n arr = [int(i) for i in str(num)]\n odd, even = [], []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n odd.sort()\n even.sort()\n res = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n res = res*10 + even.pop()\n else:\n res = res*10 + odd.pop()\n return res\n```
31
1
['Python', 'Python3']
9
largest-number-after-digit-swaps-by-parity
Count Array
count-array-by-votrubac-06zg
Perhaps not as concise - shooting for efficiency (linear time and no string operations).\n\nWe count how much of each number we have in cnt.\n\nThen, we process
votrubac
NORMAL
2022-04-10T05:40:46.816468+00:00
2022-04-11T02:27:48.734234+00:00
3,701
false
Perhaps not as concise - shooting for efficiency (linear time and no string operations).\n\nWe count how much of each number we have in `cnt`.\n\nThen, we process digits in `num` right to left, determine the parity `par`, and use the smallest number with that parity from the `cnt` array.\n\nWe start from `0` for even, and from `1` for odd. If the count of a number reaches zero, we move up to the next number with the same parity (0 -> 2, 1 -> 3, and so on).\n\n**C++**\n```cpp\nint largestInteger(int num) {\n int cnt[10] = {}, p[2] = {0, 1}, res = 0;\n for (int n = num; n > 0; n /= 10)\n ++cnt[n % 10];\n for (long long n = num, mul = 1; n > 0; n /= 10, mul *= 10) {\n int par = n % 10 % 2 == 1;\n while (cnt[p[par]] == 0)\n p[par] += 2;\n res += mul * p[par];\n --cnt[p[par]];\n }\n return res;\n}\n```
30
0
['C']
7
largest-number-after-digit-swaps-by-parity
✅ C++ | Priority queue | Easy & Concise | O(NlogN )
c-priority-queue-easy-concise-onlogn-by-r1c98
\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s=to_string(num); //first covert the num into a string for easy traversal\n
rupam66
NORMAL
2022-04-10T05:32:49.695668+00:00
2022-04-10T07:19:53.283279+00:00
2,358
false
```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s=to_string(num); //first covert the num into a string for easy traversal\n priority_queue<int> odd, even; // then take 2 priority queue odd & even\n for(auto x: s){\n int tmp=x-\'0\'; // covert char to int\n if(tmp%2==0) even.push(tmp); // if tmp is even the push it into even priority queue\n else odd.push(tmp); // else tmp is odd & the push it into odd priority queue\n }\n\t\t// now traverse the string and find whether it is a odd no.\'s position or even no.\'s position\n for(auto& x: s){\n int tmp=x-\'0\'; // converting char to int\n if(tmp%2==0) x= even.top()+\'0\', even.pop(); // if it is even no.\'s position then put there, even priority queue\'s top element & pop that element\n else x= odd.top()+\'0\', odd.pop(); // else it is odd no.\'s position so put there, odd priority queue\'s top element & pop that element\n }\n return stoi(s); // finally convert the string into int and return it!\n }\n};\n\n// P.S: here one more thing why i\'ve written +\'0\' with the top() element?\n// - As in priority queue I\'m using int, so to convert it into a char i\'ve used " +\'0\' " [ascii sum]\n```\n\n**If you like this please upvote!**
29
0
['C', 'Sorting', 'Heap (Priority Queue)']
6
largest-number-after-digit-swaps-by-parity
sorting odd and even
sorting-odd-and-even-by-yashgarala29-drl1
\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int> odd,even,arr;\n while(num)\n {\n int digit =num%10;
yashgarala29
NORMAL
2022-04-10T04:01:39.945990+00:00
2022-04-10T04:01:39.946015+00:00
2,555
false
```\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int> odd,even,arr;\n while(num)\n {\n int digit =num%10;\n num=num/10;\n if(digit%2==0)\n {\n even.push_back(digit);\n }\n else\n {\n odd.push_back(digit);\n }\n arr.push_back(digit);\n \n }\n sort(even.rbegin(),even.rend());\n sort(odd.rbegin(),odd.rend());\n \n int o=0,e=0;\n int ans=0;\n int n=arr.size();\n for(int i=0;i<arr.size();i++)\n {\n if(arr[n-1-i]%2==0)\n {\n ans=ans*10+even[e++];\n }\n else\n {\n ans=ans*10+odd[o++];\n }\n }\n return ans;\n }\n};\n```
19
1
['Sorting']
2
largest-number-after-digit-swaps-by-parity
[Java] solution using two priority queue
java-solution-using-two-priority-queue-b-m4f8
\nclass Solution {\n public int largestInteger(int num) {\n PriorityQueue<Integer> opq = new PriorityQueue<>();\n PriorityQueue<Integer> epq =
alan24
NORMAL
2022-04-10T04:19:27.340073+00:00
2022-04-10T04:19:27.340101+00:00
2,089
false
```\nclass Solution {\n public int largestInteger(int num) {\n PriorityQueue<Integer> opq = new PriorityQueue<>();\n PriorityQueue<Integer> epq = new PriorityQueue<>();\n int bnum = num;\n while(num>0){\n int cur = num%10;\n if(cur%2==1){\n opq.add(cur);\n }else{\n epq.add(cur);\n }\n num /= 10;\n }\n StringBuilder sb = new StringBuilder();\n num = bnum;\n while(num>0){\n int cur = num%10;\n if(cur%2==1)\n sb.insert(0, opq.poll());\n else\n sb.insert(0, epq.poll());\n num /= 10;\n }\n return Integer.parseInt(sb.toString());\n }\n}\n```\n**please leave a like if you found this helpful\nand leave a comment if you have any question\nhappy coding : )**
16
0
['Heap (Priority Queue)', 'Java']
8
largest-number-after-digit-swaps-by-parity
[Java] Counting Sort solution [Faster than 100.00% ]
java-counting-sort-solution-faster-than-qez6k
Intuition\n1. Get frequency of all the digits from 0-9\n2. Construct the newNumber by taking the maximum possible digit for that location => odd/even is determi
manidh
NORMAL
2022-04-10T04:22:56.401419+00:00
2022-04-10T04:22:56.401442+00:00
2,154
false
**Intuition**\n1. Get frequency of all the digits from 0-9\n2. Construct the newNumber by taking the maximum possible digit for that location => odd/even is determined by the parity of the value in the original number provided\n\n```\n public int largestInteger(int num) {\n char[] nums = Integer.toString(num).toCharArray();\n \n //Calculate the frequency of each digit from 0 - 9\n int[] frequency = new int[10];\n for (int index = 0; index < nums.length; index++) {\n frequency[nums[index] - \'0\']++;\n }\n \n int newNumber = 0;\n int evenIndex = 8; // corresponds to the number 8 \n int oddIndex = 9; // corresponds to the number 9 \n\n // construct the number\n for(int index = 0; index < nums.length; index++) {\n // If the parity of number in current index is even\n if(nums[index] % 2 == 0) {\n // Get first even digit of non-zero frequency\n while(frequency[evenIndex]==0) {\n evenIndex -= 2;\n }\n frequency[evenIndex]--;\n newNumber = newNumber*10 + evenIndex;\n } else {\n // If the parity of number in current index is odd\n // Get first odd digit of non-zero frequency\n while(frequency[oddIndex]==0) {\n oddIndex -= 2;\n }\n frequency[oddIndex]--;\n newNumber = newNumber*10 + oddIndex;\n }\n }\n \n return newNumber;\n }\n```
12
0
['Sorting', 'Counting Sort', 'Java']
3
largest-number-after-digit-swaps-by-parity
C++ || Easy Solution || O(n^2)
c-easy-solution-on2-by-raghav_maskara-vlyl
Approach-\n store all digits in an array\n run two loops and check if the second element is greater than the first and their parity is same or not\n If yes, we
raghav_maskara
NORMAL
2022-04-10T04:32:49.398001+00:00
2022-04-10T04:34:13.093101+00:00
967
false
**Approach-**\n* store all digits in an array\n* run two loops and check if the second element is greater than the first and their parity is same or not\n* If yes, we swap the elements.\n* Reconstruct the number using the modified array.\n\n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int>temp;\n int x=num;\n while(x>0){\n int y=x%10;\n temp.push_back(y);\n x=x/10;\n }\n reverse(temp.begin(),temp.end());\n int n=temp.size();\n for(int i=0;i<n;i++){\n int curr=temp[i];\n int p=curr%2;\n int j=i+1;\n while(j<n){\n if(temp[j]>temp[i] and temp[j]%2==p)\n swap(temp[j],temp[i]);\n j++;\n }\n }\n long long int res=0;\n for(int i=0;i<temp.size();i++){\n res+=temp[i];\n res*=10;\n }\n return res/10;\n }\n};\n```
9
2
['C']
2
largest-number-after-digit-swaps-by-parity
Largest Number After Digit Swaps By Parity || Efficient Approach
largest-number-after-digit-swaps-by-pari-wcyt
IntuitionThe problem is to rearrange the digits of an integer num to form the largest possible number while maintaining the parity (even or odd) of each digit i
theCode_X
NORMAL
2025-01-02T13:28:00.493175+00:00
2025-01-02T13:28:00.493175+00:00
1,193
false
# Intuition The problem is to rearrange the digits of an integer num to form the largest possible number while maintaining the parity (even or odd) of each digit in its original position. The core idea is to separate the even and odd digits, sort them in descending order, and then reconstruct the number while preserving the original parity of each position. <!-- Describe your first thoughts on how to solve this problem. --> # Approach 1. Segregate Digits: - Convert the number into a string to extract individual digits. - Use two max-heaps (priority queues) to store the even and odd digits separately, sorted in descending order. 2. Reconstruct the Number: - Traverse the digits of the original number. - For each digit, replace it with the largest available digit of the same parity from the respective heap. 3. Return the Result: - Convert the reconstructed string into an integer and return it. <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: $$O(dlogd)$$ - Extracting digits: O(d), where d is the number of digits in num. - Heap operations (insertion and extraction): O(dlogd). <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(d)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int largestInteger(int num) { PriorityQueue<Integer> evenMaxHeap = new PriorityQueue<>(Collections.reverseOrder()); PriorityQueue<Integer> oddMaxHeap = new PriorityQueue<>(Collections.reverseOrder()); // Store the digits of the number and segregate even and odd digits String numStr = String.valueOf(num); for (char ch : numStr.toCharArray()) { int digit = ch - '0'; if (digit % 2 == 0) { evenMaxHeap.add(digit); } else { oddMaxHeap.add(digit); } } StringBuilder result = new StringBuilder(); // Construct the largest integer by replacing digits with those from the heaps for (char ch : numStr.toCharArray()) { int digit = ch - '0'; if (digit % 2 == 0) { result.append(evenMaxHeap.poll()); } else { result.append(oddMaxHeap.poll()); } } return Integer.parseInt(result.toString()); } } ``` If you understand my solution and useful for your DSA journey then upvote me to build my confidence frds ! 😊
7
0
['Heap (Priority Queue)', 'Java']
0
largest-number-after-digit-swaps-by-parity
Wrong testcase for input -> 247 !!! output should be 742.
wrong-testcase-for-input-247-output-shou-mbu9
Please help me to figure it out where i\'m lacking!\n\n\n\n\n\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\
binayKr
NORMAL
2022-04-27T08:15:09.294816+00:00
2022-04-28T06:33:24.821367+00:00
352
false
## ***Please help me to figure it out where i\'m lacking!***\n\n![image](https://assets.leetcode.com/users/images/ff37dc75-8ae4-4230-b868-04c6e15c1aba_1651047084.092038.png)\n\n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n int n = s.size();\n priority_queue<int> se,so;\n for(int i=0; i<n; i++)\n {\n if(i%2==0) se.push(s[i]-\'0\');\n else so.push(s[i]-\'0\');\n }\n \n for(int i=0; i<n; i++)\n {\n if(i%2==0){\n int t = se.top() + 48;\n se.pop();\n s[i] = t;\n }\n else{ \n int t = so.top() + 48;\n so.pop();\n s[i] = t;\n }\n }\n return stoi(s);\n }\n};\n```\n\n# **Figured out the mistake....hence adding the correct solution below!**\n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n int n = s.size();\n priority_queue<int> se,so;\n for(int i=0; i<n; i++)\n {\n if((s[i]-\'0\')%2==0) se.push(s[i]-\'0\');\n else so.push(s[i]-\'0\');\n }\n \n for(int i=0; i<n; i++)\n {\n if((s[i]-\'0\')%2==0){\n int t = se.top() + 48;\n se.pop();\n s[i] = t;\n }\n else{ \n int t = so.top() + 48;\n so.pop();\n s[i] = t;\n }\n }\n return stoi(s);\n }\n};\n```\n\n
7
0
[]
2
largest-number-after-digit-swaps-by-parity
Sort and put them back || With intuition || 7 lines
sort-and-put-them-back-with-intuition-7-fhdmk
Intuition:\n We can simply extract the even and odd in different strings and sort them in decreasing order and put them back in main string.\n Problem Occurs :
xxvvpp
NORMAL
2022-04-10T04:06:49.428021+00:00
2022-04-10T06:07:43.464685+00:00
1,000
false
**Intuition**:\n We can simply `extract the even and odd in different strings and sort them in decreasing order and put them back in main string`.\n **Problem Occurs** : How we will differentiate the even and odd position for puting the odd and even back.\n **Solution**: We will put all even at even element position and all odd at odd element position.\n \n **Algorithm**:\n + Extract \n + sort\n + place them back\n # C++ \n\tint largestInteger(int num) {\n string p= to_string(num) , odd="", even="";\n for(int i=0;i<p.size();i++){\n if((p[i]-\'0\')%2==0) even+= p[i]; else odd+= p[i]; \n\t\t}\n sort(rbegin(odd),rend(odd));\n sort(rbegin(even),rend(even));\n for(int i=0,j=0,k=0;i<p.size();i++) p[i]= (p[i]-\'0\')%2==0? even[j++] : odd[k++];\n return stoi(p);\n }\n**Worst Time** - O( log(num)* log(log(num)) ) ==> For sorting\n**Maximum Space** - O(log(num))
7
0
['C']
1
largest-number-after-digit-swaps-by-parity
C++ Solution || Fully Commented || 💯% fast
c-solution-fully-commented-fast-by-nitin-7a6z
\n\n# Code\n\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<int>odd,even;//To store the even and odd values in descending o
NitinSingh77
NORMAL
2023-03-09T15:58:42.609726+00:00
2023-03-23T15:37:01.170353+00:00
1,358
false
\n\n# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<int>odd,even;//To store the even and odd values in descending order separately;\n\n vector<int>seq,nitin; //Seq vector to store the sequence of odd and even occurrences and nitin vector to store the values of priority queue in order;\n\n while(num>0) \n // To split and store the even digits in even priority queue and odd in odd priority queue and all the digits in seq vector;\n { \n int last=num%10;\n if(last%2==0)\n {\n even.emplace(last);\n }\n else\n {\n odd.emplace(last);\n }\n num=num/10;\n seq.emplace_back(last);\n }\n reverse(seq.begin(),seq.end());//reverse the vectore since the digits are stored in reverse order in the vector.\n int ans=0;\n for(int i=0;i<seq.size();i++) //store the digits from even and odd priority queue into nitin vector according to the occurrences.\n\n {\n if(seq[i]%2==0)\n {\n nitin.emplace_back(even.top());\n even.pop();\n }\n else\n {\n nitin.emplace_back(odd.top());\n odd.pop();\n }\n\n }\n for(int i=0;i<nitin.size();i++) //Store the final values in answer.\n {\n ans=ans*10+nitin[i];\n }\n return ans;\n }\n};\n```
6
0
['Heap (Priority Queue)', 'C++']
0
largest-number-after-digit-swaps-by-parity
Python||Heap soln
pythonheap-soln-by-nitishjha21-y5mu
```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n evenHeap = []\n oddHeap = []\n heapq.heapify(evenHeap)\n heap
NitishJha21
NORMAL
2022-04-27T08:23:08.444180+00:00
2022-04-27T08:23:08.444221+00:00
713
false
```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n evenHeap = []\n oddHeap = []\n heapq.heapify(evenHeap)\n heapq.heapify(oddHeap)\n num = list(str(num))\n for i in num:\n if int(i)%2:\n heapq.heappush(oddHeap,-int(i))\n else:\n heapq.heappush(evenHeap,-int(i))\n for ind,val in enumerate(num):\n if int(val)%2:#odd\n num[ind] = -heapq.heappop(oddHeap)\n else:\n num[ind] = -heapq.heappop(evenHeap)\n num = map(str,num)\n return int(\'\'.join(num))\n
6
0
['Heap (Priority Queue)', 'Python']
1
largest-number-after-digit-swaps-by-parity
👉 Simple Solution || Sorting || C++ ✅✅
simple-solution-sorting-c-by-ganesh_1221-0vu5
\n\nclass Solution {\npublic:\n int largestInteger(int num) {\n \n string s=to_string(num);\n vector<pair<int,char>>odd,even; \n
Ganesh_1221
NORMAL
2023-07-19T18:44:39.285462+00:00
2023-07-19T18:44:39.285483+00:00
1,952
false
```\n\nclass Solution {\npublic:\n int largestInteger(int num) {\n \n string s=to_string(num);\n vector<pair<int,char>>odd,even; \n int i=0,j=0;\n \n for(auto i:s){\n if((i-\'0\')%2==0)even.push_back({i-\'0\',i}); // store pair like {2,\'2\'}\n else odd.push_back({i-\'0\',i});\n }\n sort(odd.rbegin(),odd.rend());\n sort(even.rbegin(),even.rend());\n \n string str="";\n for(auto x:s){\n \n if((x-\'0\')%2==0){\n str+=even[i].second; // add second element of pair\n i++;\n }else{\n str+=odd[j].second;\n j++;\n }\n \n }\n \n return stoi(str);\n }\n};\n\n```
5
0
[]
0
largest-number-after-digit-swaps-by-parity
Largest Number After Digit Swaps by Parity Solution in C++
largest-number-after-digit-swaps-by-pari-bhcp
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
The_Kunal_Singh
NORMAL
2023-05-16T17:27:52.393735+00:00
2023-05-16T17:27:52.393777+00:00
676
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)$$ -->\nO(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n string ans;\n int i, j=0, k=0;\n vector<int> even;\n vector<int> odd;\n for(i=0 ; i<s.size() ; i++)\n {\n if((int)s[i]%2==0)\n even.push_back((int)s[i]);\n else\n odd.push_back((int)s[i]);\n }\n\n sort(even.begin(), even.end(), greater<int>());\n sort(odd.begin(), odd.end(), greater<int>());\n\n for(i=0 ; i<s.size() ; i++)\n {\n if((int)s[i]%2==0)\n {\n ans += even[j];\n j++;\n }\n else\n {\n ans += odd[k];\n k++;\n }\n }\n return stoi(ans);\n }\n};\n```\n![upvote new.jpg](https://assets.leetcode.com/users/images/a34fc527-734d-40fb-87ef-bc851f676b4b_1684258064.377837.jpeg)\n
5
0
['C++']
0
largest-number-after-digit-swaps-by-parity
easy
easy-by-qwerysingr-p9xd
\nclass Solution {\npublic:\n int largestInteger(int numb) {\n \n int num = numb;\n vector<int> e, o, n;\n while (num) {\n
qwerysingr
NORMAL
2022-05-08T05:53:33.816963+00:00
2022-05-08T05:53:33.817002+00:00
253
false
```\nclass Solution {\npublic:\n int largestInteger(int numb) {\n \n int num = numb;\n vector<int> e, o, n;\n while (num) {\n int d = num % 10;\n if (d & 1) o.push_back(d);\n else e.push_back(d);\n num /= 10;\n }\n \n sort(begin(o), end(o), greater<int>());\n sort(begin(e), end(e), greater<int>());\n \n\n int res = 0;\n while (numb) {\n n.push_back(numb%10);\n numb /= 10;\n }\n \n reverse(begin(n), end(n));\n \n int c(0), d(0);\n for (auto i : n) {\n if (i & 1) res = res*10 + o[c++];\n else res = res*10 + e[d++];\n }\n return res;\n }\n};\n```
5
0
[]
0
largest-number-after-digit-swaps-by-parity
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-i4eh
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n int largestInteger(int num) \n {\n string s = to_stri
shishirRsiam
NORMAL
2024-06-19T21:14:05.467292+00:00
2024-06-19T21:14:05.467310+00:00
473
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) \n {\n string s = to_string(num);\n string even, odd;\n for(auto ch:s)\n {\n if(ch%2) odd.push_back(ch);\n else even.push_back(ch);\n }\n\n sort(rbegin(even), rend(even));\n sort(rbegin(odd), rend(odd));\n int evenidx = 0, oddidx = 0, n = s.size();\n for(int i=0;i<n;i++)\n {\n if(s[i]%2) s[i] = odd[oddidx++];\n else s[i] = even[evenidx++];\n }\n return stoi(s);\n }\n};\n```
4
0
['String', 'Sorting', 'C++']
3
largest-number-after-digit-swaps-by-parity
Both Max Heap and Sorting Solutions with Explanations! 🔢 % 🔥
both-max-heap-and-sorting-solutions-with-3v61
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves rearranging the digits of a given number such that the new number
sirsebastian5500
NORMAL
2024-06-09T23:16:36.997703+00:00
2024-06-09T23:18:35.722724+00:00
267
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves rearranging the digits of a given number such that the new number is the largest possible while maintaining the relative positions of even and odd digits. This means we need to sort the even digits and odd digits separately and then place them back into their respective positions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Max Heap Approach:**\n - Convert the number to a string to handle individual digits easily.\n - Use two max heaps (implemented as negative min heaps in Python) to separately store the even and odd digits.\n - Iterate over the digits of the number and push each digit into the appropriate heap (even or odd).\n - Construct the largest possible number by popping the largest elements from the respective heaps based on the original parity (even or odd) of each digit.\n\n2. **Sorting Approach:**\n - Convert the number to a string for easier manipulation of digits.\n - Extract and sort the even and odd digits separately in descending order.\n - Reconstruct the number by iterating over the original digits and replacing each digit with the largest available digit of the same parity from the sorted lists.\n\n# Complexity\n- Time complexity:\n - **Max Heap Approach:** $$O(n \\log n)$$ because each insertion and removal operation in the heap takes $$O(\\log n)$$ time.\n - **Sorting Approach:** $$O(n \\log n)$$ because sorting the even and odd digits takes $$O(n \\log n)$$ time.\n \n- Space complexity:\n - Both approaches use additional space to store the digits and heaps/lists, resulting in $$O(n)$$ space complexity.\n\n# Code\n```python\nclass Solution:\n def largestInteger(self, num: int) -> int:\n # Max Heap\n num = str(num) \n even_heap, odd_heap = [], []\n largest_num = []\n\n for digit_stg in num: \n if int(digit_stg) % 2 == 0:\n heapq.heappush(even_heap, -int(digit_stg))\n else:\n heapq.heappush(odd_heap, -int(digit_stg))\n \n for digit_stg in num: \n if int(digit_stg) % 2 == 0:\n largest_num.append(str(-heapq.heappop(even_heap)))\n else:\n largest_num.append(str(-heapq.heappop(odd_heap)))\n\n return int("".join(largest_num))\n\n # O(n log n) time.\n # O(n) space.\n \n\n def largestInteger2(self, num: int) -> int:\n # Sorting\n num_str = str(num)\n even_digits = sorted([int(d) for d in num_str if int(d) % 2 == 0], reverse=True)\n odd_digits = sorted([int(d) for d in num_str if int(d) % 2 != 0], reverse=True)\n result = []\n even_index, odd_index = 0, 0\n \n for digit in num_str:\n if int(digit) % 2 == 0:\n result.append(str(even_digits[even_index]))\n even_index += 1\n else:\n result.append(str(odd_digits[odd_index]))\n odd_index += 1\n \n return int("".join(result))\n\n # O(n log n) time.\n # O(n) space.\n```\n\nUPVOTE IF HELPFUL \uD83E\uDD19\nTHANKS
4
0
['Python3']
0
largest-number-after-digit-swaps-by-parity
C++ Solution || 100% Fast || Easy to Understand
c-solution-100-fast-easy-to-understand-b-27nx
Approach:\n1. We will declare two Priority Queues with the name odd and even to store the odd and even digits from the given number.\n2. We will declare two arr
01_Unzila
NORMAL
2023-02-28T13:48:34.068701+00:00
2023-02-28T13:48:34.068783+00:00
764
false
**Approach:**\n1. We will declare two Priority Queues with the name **odd** and **even** to store the odd and even digits from the given number.\n2. We will declare two arrays, array **digit** to store all the digits of the given number and other array **res** to store the digits of the required number.\nWe will store all the digits of the number in the **digit** array and also the odd digits in the **odd** priority queue and even digits in the **even** priority queue.\n3. Now we will traverse the **digit** array. If we find the **digit[i]** is odd, we will store the top element of the **odd** priority queue in the **res** array and will pop the element from the priority queue. And if the **digit[i]** is even, we will store the top element of the **even** priority queue in the **res** array and will pop the element from the priority queue.\n4. At the end, we have all the digits of the required number in the **res** array stored in the sequence. We will simply obtain the required number from this array.\n\n\n```\nclass Solution {\npublic:\n int largestInteger(int num)\n {\n priority_queue<int> odd;\n priority_queue<int> even;\n vector<int> digit, res;\n \n\t\t// Extracting Digits from num\n while(num)\n {\n int rem=num%10;\n digit.push_back(rem);\n if(rem%2==0) even.push(rem);\n else odd.push(rem);\n num/=10;\n }\n \n for(int i=digit.size()-1;i>=0;i--)\n {\n if(digit[i]%2==0){\n res.push_back(even.top());\n even.pop();\n } \n else{\n res.push_back(odd.top());\n odd.pop();\n }\n }\n \n\t\t// Obtaining the required Number\n int maxNum=0;\n for(int i=0;i<res.size();i++)\n {\n maxNum=maxNum*10+res[i];\n }\n \n return maxNum;\n }\n};\n```
4
0
['C', 'Heap (Priority Queue)', 'C++']
0
largest-number-after-digit-swaps-by-parity
Python easy solution using heap | faster than 99%
python-easy-solution-using-heap-faster-t-tkxg
\nI have maintained two heaps: odd_x and even_x\nIf number is odd push into odd_x else push intoeven_x, also I am adding true (wherever odd number is encountere
wilspi
NORMAL
2022-08-08T02:05:46.458862+00:00
2022-08-08T02:05:46.458890+00:00
1,406
false
\nI have maintained two heaps: `odd_x` and `even_x`\nIf number is odd push into `odd_x` else push into`even_x`, also I am adding true (wherever odd number is encountered) so that its easy to track positions of odd numbers\n\nFor generating ans, I am popping out highest odd number for positions using heap where odd numbers were present (`ans[i] = -heapq.heappop(odd_x)`) \nand similarly doing for even numbers\n\n```python\n\nclass Solution:\n def largestInteger(self, num: int) -> int:\n\n odd_x = []\n even_x = []\n ans = []\n for i in str(num):\n i = int(i)\n if i % 2:\n odd_x.append(-i)\n ans.append(True)\n else:\n even_x.append(-i)\n ans.append(False)\n\n heapq.heapify(odd_x)\n heapq.heapify(even_x)\n\n for i in range(len(ans)):\n if ans[i]:\n ans[i] = -heapq.heappop(odd_x)\n else:\n ans[i] = -heapq.heappop(even_x)\n\n return int("".join(str(n) for n in ans))\n\n```
4
0
['Heap (Priority Queue)', 'Python', 'Python3']
1
largest-number-after-digit-swaps-by-parity
Java || 2 Priority Queues || Easy
java-2-priority-queues-easy-by-devansh28-a2a4
\nclass Solution {\n public int largestInteger(int num) {\n String numStr = Integer.toString(num);\n PriorityQueue<Integer> oddPQ = new Priorit
devansh2805
NORMAL
2022-06-02T10:19:20.586237+00:00
2022-06-02T10:19:20.586272+00:00
589
false
```\nclass Solution {\n public int largestInteger(int num) {\n String numStr = Integer.toString(num);\n PriorityQueue<Integer> oddPQ = new PriorityQueue<>(Collections.reverseOrder());\n PriorityQueue<Integer> evenPQ = new PriorityQueue<>(Collections.reverseOrder());\n for(char digit: numStr.toCharArray()) {\n int value = digit - \'0\';\n if(value % 2 == 0) {\n evenPQ.offer(value);\n } else {\n oddPQ.offer(value);\n }\n }\n int answer = 0;\n for(char digit: numStr.toCharArray()) {\n answer *= 10;\n if((digit - \'0\') % 2 == 0) {\n answer += evenPQ.poll();\n } else {\n answer += oddPQ.poll();\n }\n }\n return answer;\n }\n}\n```
4
0
['Heap (Priority Queue)', 'Java']
0
largest-number-after-digit-swaps-by-parity
Simple | Easy | Sorting
simple-easy-sorting-by-abhinandanmishra1-9br0
\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int> pos;\n vector<int> even,odd;\n int n=num;\n while(n>0){
abhinandanmishra1
NORMAL
2022-04-10T04:56:07.187842+00:00
2022-04-10T04:56:07.187875+00:00
400
false
```\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int> pos;\n vector<int> even,odd;\n int n=num;\n while(n>0){\n int k=n%10;\n if(k&1){\n odd.push_back(k);\n pos.push_back(0);\n }else{\n even.push_back(k);\n pos.push_back(1);\n }\n n/=10;\n }\n reverse(pos.begin(),pos.end());\n sort(even.rbegin(),even.rend());\n sort(odd.rbegin(),odd.rend());\n int ans=0;\n int i=0,j=0,k=0;\n while(k<pos.size()){\n if(pos[k]==1){\n ans=ans*10+even[i++];\n }else{\n ans=ans*10+odd[j++];\n }\n k++;\n }\n return ans;\n }\n};\n```
4
0
['C', 'Sorting']
0
largest-number-after-digit-swaps-by-parity
C++ || SORTING || COMMENTED
c-sorting-commented-by-sahiltuli_31-bfby
\nint largestInteger(int num) {\n \n \n //the idea is to get all even and odd number seaparate\n vector<int> odd;\n vector<in
sahiltuli_31
NORMAL
2022-04-10T04:04:26.649855+00:00
2022-04-10T04:05:47.641407+00:00
441
false
```\nint largestInteger(int num) {\n \n \n //the idea is to get all even and odd number seaparate\n vector<int> odd;\n vector<int> even;\n \n string n = to_string(num);\n string nn = n;\n \n for(int i = 0;i < n.size();i++)\n {\n int k = n[i] - \'0\';\n if(k&1)\n {\n odd.push_back(k);\n }\n else\n {\n even.push_back(k);\n }\n }\n \n //lets sort them in decreasing order\n sort(odd.begin(),odd.end());\n sort(even.begin(),even.end());\n reverse(even.begin(),even.end());\n reverse(odd.begin(),odd.end());\n \n //now traverse the original string and put even number where there was even number originally now just in sorted order\n //same for odd numbers and their positions\n\n int i = 0;\n int j = 0;\n string ans = "";\n for(int m = 0;m < nn.size();m++)\n {\n int k = nn[m]-\'0\';\n //finding if there was odd or even at this position\n if(k&1)\n {\n ans += odd[i]+\'0\';\n i++;\n }\n else\n {\n ans += even[j]+\'0\';\n j++;\n }\n }\n \n return stoi(ans);\n \n }\n};\n```\n
4
0
['C', 'Sorting']
1
largest-number-after-digit-swaps-by-parity
[C++] || Brute
c-brute-by-4byx-zfq8
\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n int n = s.length();\n for(int i = 0 ; i < n ;
4byx
NORMAL
2022-04-10T04:00:48.869795+00:00
2022-04-10T04:00:48.869830+00:00
637
false
```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n int n = s.length();\n for(int i = 0 ; i < n ; i++){\n int f = i;\n int maxi = s[i]-\'0\';\n for(int j = i+1 ; j < n ; j++){\n if((s[i]-\'0\')%2 == 1 and (s[j]-\'0\')%2 == 1 and (s[j]-\'0\')>maxi){\n maxi = s[j]-\'0\';\n f = j;\n }else if((s[i]-\'0\')%2 == 0 and (s[j]-\'0\')%2 == 0 and (s[j]-\'0\')>maxi){\n maxi = s[j]-\'0\';\n f = j;\n }\n }\n swap(s[i],s[f]);\n }\n return stoi(s);\n }\n};\n```
4
1
['C']
0
largest-number-after-digit-swaps-by-parity
SIMPLE MAX-HEAP C++ SOLUTION
simple-max-heap-c-solution-by-jeffrin200-i98p
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
Jeffrin2005
NORMAL
2024-08-02T09:54:54.522535+00:00
2024-08-02T09:54:54.522566+00:00
204
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(D log D), where D is the number of digits in the number.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(D), where D is the number of digits in the number.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n priority_queue<int>evenDigits;\n priority_queue<int>oddDigits;\n // Separate digits into even and odd heaps\n for(auto&c : s){\n int digit = c - \'0\';\n if(digit % 2 == 0){\n evenDigits.push(digit);\n }else{\n oddDigits.push(digit);\n }\n }\n\n // Reconstruct the number with the largest digits from heaps in their respective positions\n string result;\n for(auto&c : s){\n int digit = c - \'0\';\n if(digit % 2 == 0){\n result+= \'0\' + evenDigits.top();\n evenDigits.pop();\n }else{\n result += \'0\' + oddDigits.top();\n oddDigits.pop();\n }\n }\n return stoi(result);\n }\n};\n```
3
0
['C++']
0
largest-number-after-digit-swaps-by-parity
Java Solution
java-solution-by-janhvi__28-t56b
\nclass Solution {\n public int largestInteger(int num) {\n int[] ans = new int[10];\n int x = num;\n while (x != 0) {\n ans[
Janhvi__28
NORMAL
2022-11-07T07:37:51.621442+00:00
2022-11-07T07:37:51.621478+00:00
1,409
false
```\nclass Solution {\n public int largestInteger(int num) {\n int[] ans = new int[10];\n int x = num;\n while (x != 0) {\n ans[x % 10]++;\n x /= 10;\n }\n x = num;\n int result = 0;\n int t = 1;\n while (x != 0) {\n int v = x % 10;\n x /= 10;\n for (int y = 0; y < 10; ++y) {\n if (((v ^ y) & 1) == 0 && ans[y] > 0) {\n ans[y]--;\n result += y * t;\n t *= 10;\n break;\n }\n }\n }\n return result;\n }\n}\n```
3
0
['Java']
0
largest-number-after-digit-swaps-by-parity
Odd-Even Approach ||Using Strings || Explained With Comments || C++
odd-even-approach-using-strings-explaine-590p
\nclass Solution {\npublic:\n int largestInteger(int num) {\n \n string s = to_string(num);\n \n string even=""; // stores all even no.
shubh08am
NORMAL
2022-09-17T10:39:36.492081+00:00
2022-09-17T10:39:36.492126+00:00
518
false
```\nclass Solution {\npublic:\n int largestInteger(int num) {\n \n string s = to_string(num);\n \n string even=""; // stores all even no.\n string odd=""; // stores all odd no.\n string ans=""; // stores result\n \n //storing odd and even no.\n for(auto&it:s) {\n if((it-\'0\') &1) odd+=it;\n else even+=it;\n }\n \n // sorting them in descending order\n sort(odd.begin(),odd.end(),greater<int>());\n sort(even.begin(),even.end(),greater<int>());\n\n // this pointer points at odd and even strings respectively\n int odd_start=0;\n int even_start=0;\n \n//Now,iterate through s and if odd number is there replace with largest odd no. and similarly for even no. and move pointer to next position\n for(int i=0;i<s.size();i++){\n if((s[i]-\'0\')&1){ \n ans+=odd[odd_start] ;\n odd_start++;\n }\n \n else{\n ans+=even[even_start] ;\n even_start++;\n }\n }\n // convert ans to string \n int res = stoi(ans);\n return res;\n }\n};\n```\n\n```\nIf you find this solutions to be helpful do upvote..It keeps me motivated :)\n```
3
0
['String', 'C']
0
largest-number-after-digit-swaps-by-parity
Using priority queue C++ 0 ms, 100% faster
using-priority-queue-c-0-ms-100-faster-b-1ik0
\nint largestInteger(int num) {\n string s=to_string(num);\n int n=s.size();\n priority_queue<int> odd;\n priority_queue<int> even;\
Shreedhar_Kushwaha
NORMAL
2022-09-12T06:42:26.334669+00:00
2022-09-12T06:42:26.334720+00:00
525
false
```\nint largestInteger(int num) {\n string s=to_string(num);\n int n=s.size();\n priority_queue<int> odd;\n priority_queue<int> even;\n int result=0;\n for(int i=0;i<n;i++){\n if((s[i]-\'0\')%2 ==0)\n even.push(s[i]-\'0\');\n else\n odd.push(s[i]-\'0\');\n }\n \n for(int i=0;i<n;i++){\n result=result*10;\n if((s[i]-\'0\')%2 ==0){\n result+=even.top();\n even.pop();\n }\n else {\n result+=odd.top();\n odd.pop();\n }\n }\n return result;\n }\n```
3
0
['C', 'Heap (Priority Queue)', 'C++']
0
largest-number-after-digit-swaps-by-parity
C++|| 0 ms || Easy to understand
c-0-ms-easy-to-understand-by-rishabhteli-41te
\nclass Solution {\npublic:\n bool issame(int a, int b){\n if(a%2==0 && b%2==0) return true;\n else if(a%2!=0 && b%2!=0) return true;\n
rishabhteli14
NORMAL
2022-04-12T12:23:02.543517+00:00
2023-07-06T08:42:14.423484+00:00
115
false
```\nclass Solution {\npublic:\n bool issame(int a, int b){\n if(a%2==0 && b%2==0) return true;\n else if(a%2!=0 && b%2!=0) return true;\n return false;\n }\n \n int largestInteger(int num) {\n string str = to_string(num);\n if(str.length()==1){\n return num;\n }\n int a = 0;\n int b = 1;\n for(int i =0;i<str.length();){\n if(issame(str[i],str[b])){\n if(str[i]<str[b]){\n swap(str[i],str[b]);\n }\n }\n b++;\n if(b==str.length()){\n i++;\n b=i;\n }\n }\n return stoi(str);\n }\n};\n```\n\nAny suggestions are highly appreciated...
3
0
['C++']
0
largest-number-after-digit-swaps-by-parity
Rust solution
rust-solution-by-bigmih-sm7w
\nimpl Solution {\n pub fn largest_integer(num: i32) -> i32 {\n use std::collections::BinaryHeap;\n\n let mut num = num as usize;\n let
BigMih
NORMAL
2022-04-10T11:32:11.909191+00:00
2022-04-10T12:11:28.525991+00:00
101
false
```\nimpl Solution {\n pub fn largest_integer(num: i32) -> i32 {\n use std::collections::BinaryHeap;\n\n let mut num = num as usize;\n let mut evens_odds = [BinaryHeap::new(), BinaryHeap::new()];\n let mut digits = Vec::new();\n\n while num > 0 {\n let dig = num % 10;\n evens_odds[dig % 2].push(dig as i32);\n digits.push(dig);\n num /= 10;\n }\n\n digits\n .iter()\n .rev()\n .fold(0, |res, &dig| 10 * res + evens_odds[dig % 2].pop().unwrap())\n }\n}\n```
3
0
['Rust']
0
largest-number-after-digit-swaps-by-parity
✅ C++ | Sort Even and Odd
c-sort-even-and-odd-by-chandanagrawal23-bx8r
\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n \n vector<int>odd,even;\n \n fo
chandanagrawal23
NORMAL
2022-04-10T04:12:13.559959+00:00
2022-04-10T04:14:49.765739+00:00
278
false
```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n \n vector<int>odd,even;\n \n for(auto xt : s)\n {\n if((xt-\'0\')%2)\n odd.push_back(xt-\'0\');\n else\n even.push_back(xt-\'0\');\n }\n \n sort(odd.begin(),odd.end());\n reverse(odd.begin(),odd.end());\n \n sort(even.begin(),even.end());\n reverse(even.begin(),even.end());\n \n int i = 0;\n int j = 0;\n int ans = 0;\n for(auto xt : s)\n {\n if((xt-\'0\')%2)\n ans = ans*10 + odd[i++];\n else\n ans = ans*10 + even[j++];\n }\n return ans;\n \n }\n};\n```
3
1
['C', 'Sorting']
1
largest-number-after-digit-swaps-by-parity
Python3 O(nlogn) Solution with explanation
python3-onlogn-solution-with-explanation-omgl
The idea here is to grab all the odd and even integers separately in their own lists. We then sort the odd and even lists in descending order. Finally, we ite
condor_code
NORMAL
2022-04-10T04:01:33.239647+00:00
2022-04-10T04:06:43.117736+00:00
1,037
false
The idea here is to grab all the odd and even integers separately in their own lists. We then sort the odd and even lists in descending order. Finally, we iterate over `num`. If the current digit in num is odd, we place the largest odd digit that remains in our odd list, and vice versa if the current digit is even.\n\n\n```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n num = str(num)\n lst = [int(x) for x in num]\n odd_lst = [x for x in lst if x % 2 == 1]\n even_lst = [x for x in lst if x % 2 == 0]\n odd_lst = sorted(odd_lst, reverse=True)\n even_lst = sorted(even_lst, reverse=True)\n oi = ei = 0\n result = []\n for i, x in enumerate(num):\n xi = int(x)\n if xi % 2 == 1:\n result.append(odd_lst[oi])\n oi += 1\n else:\n result.append(even_lst[ei])\n ei += 1\n result = [str(x) for x in result]\n result = "".join(result)\n result = int(result)\n return result\n```
3
0
['Python']
1
largest-number-after-digit-swaps-by-parity
Collect the Digits into Odd and Even Heaps and Beat 100%
collect-the-digits-into-odd-and-even-hea-xqjr
IntuitionGather all even and odd digits and redistribute according to their magnitude.ApproachMake the input a string and iterate over the digit characters of t
HenryWan31
NORMAL
2025-02-02T07:35:32.629463+00:00
2025-02-02T07:35:32.629463+00:00
366
false
# Intuition Gather all even and odd digits and redistribute according to their magnitude. # Approach Make the input a string and iterate over the digit characters of the string. Along the way, collect the digits into heaps. Then redistribute the numbers from the most significant digit to the least significant digit. You need to make sure that this approach is same as swaping a pair of digits at each time. This can be easily proved by using the base case (2 digits) and induction. # Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(n)$$ # Code ```python3 [] import heapq class Solution: def largestInteger(self, num: int) -> int: odd_heap = [] even_heap = [] num = str(num) for char in num: if int(char) % 2 == 0: heapq.heappush(even_heap, -int(char)) else: heapq.heappush(odd_heap, -int(char)) res = [] for i in range(len(num)): if int(num[i]) % 2 == 0: digit = - heapq.heappop(even_heap) else: digit = - heapq.heappop(odd_heap) res.append(str(digit)) return int("".join(res)) ```
2
0
['Python3']
2
largest-number-after-digit-swaps-by-parity
leetcodedaybyday - Beats 100% with C++ and Beats 100% with Python3
leetcodedaybyday-beats-100-with-c-and-be-w94g
IntuitionThe problem requires rearranging the digits of a number to form the largest possible integer while maintaining the even/odd positions of the digits. An
tuanlong1106
NORMAL
2024-12-26T09:31:23.884293+00:00
2024-12-26T09:31:23.884293+00:00
572
false
# Intuition The problem requires rearranging the digits of a number to form the largest possible integer while maintaining the even/odd positions of the digits. An even digit can only replace another even digit, and an odd digit can only replace another odd digit. This ensures the resulting number preserves the parity structure of the original number. # Approach 1. **Extract Digits**: - Extract the digits of the number. - Separate the digits into two groups: even and odd. 2. **Sort the Groups**: - Sort the even and odd groups in descending order. This ensures that the largest digits are used first when reconstructing the number. 3. **Rebuild the Number**: - Traverse the original digits and replace each digit with the largest available digit from the corresponding group (even or odd). 4. **Combine the Digits**: - Construct the resulting number by combining the rearranged digits. # Complexity - **Time Complexity**: - Extracting digits: O(log10(n)), where n is the input number. - Sorting even and odd groups: O(log10(n) * log(log10(n))). - Rebuilding the number: O(log10(n)). - **Total**: O(log10(n) * log(log10(n))). - **Space Complexity**: - O(log10(n)) for storing digits and heaps. # Code ```cpp [] class Solution { public: int largestInteger(int num) { priority_queue<int> odd; priority_queue<int> even; vector<int> digit, res; while (num){ int n = num % 10; digit.push_back(n); if (n % 2 == 0) even.push(n); else odd.push(n); num /= 10; } for (int i = digit.size() - 1; i >= 0; i--){ if (digit[i] % 2 == 0){ res.push_back(even.top()); even.pop(); } else { res.push_back(odd.top()); odd.pop(); } } int maxNum = 0; for (int i = 0; i < res.size(); i++){ maxNum = maxNum * 10 + res[i]; } return maxNum; } }; ``` ```python3 [] class Solution: def largestInteger(self, num: int) -> int: odd, even = [], [] digits, res = [], [] while num > 0: n = num % 10 digits.append(n) if n % 2 == 0: heapq.heappush(even, -n) else: heapq.heappush(odd, -n) num //= 10 digits.reverse() for d in digits: if d % 2 == 0: res.append(-heapq.heappop(even)) else : res.append(-heapq.heappop(odd)) maxNum = 0 for digit in res: maxNum = maxNum * 10 + digit return maxNum ```
2
0
['C++', 'Python3']
0
largest-number-after-digit-swaps-by-parity
🔢 6. Priority Queue Solution !! || Simple Approach || Clean & Concise Code ! || C++ Code Reference
6-priority-queue-solution-simple-approac-nfl4
\n\ncpp [There You Go !!]\n\n int largestInteger(int n) {\n \n // Step 1\n vector<int> v;\n while(n){\n v.push_back(n%
Amanzm00
NORMAL
2024-07-12T06:28:03.394064+00:00
2024-07-12T06:28:03.394140+00:00
210
false
\n\n```cpp [There You Go !!]\n\n int largestInteger(int n) {\n \n // Step 1\n vector<int> v;\n while(n){\n v.push_back(n%10);\n n=n/10;\n }\n // Step 2\n priority_queue<int> Odd,Even;\n for(auto& i:v)\n if(i&1) Odd.push(i);\n else Even.push(i);\n\n // Step 3\n int s=v.size();\n for(int i=s-1;i>=0;i--)\n {\n if(v[i] & 1)\n { v[i]=Odd.top(); Odd.pop(); }\n else\n { v[i]=Even.top(); Even.pop(); }\n\n n=n*10+v[i];\n }\n\n return n;\n }\n\n```\n```cpp [Code Explanation With Comment\'s]\n\n int largestInteger(int n) {\n \n // Given n = 65875\n vector<int> v;\n \n // Push back Digit\'s Of n\n while(n){\n v.push_back(n%10);\n n=n/10;\n }\n // Now v = [5 7 8 5 6] : reversed n\n\n // Push Odd & Even Digits In Their Respective Priority Queue\n priority_queue<int> Odd,Even;\n for(auto& i:v)\n if(i&1) Odd.push(i);\n else Even.push(i);\n\n /* Now Odd Pq = {7, 5, 5}\n & Even Pq = {8,6} */\n\n\n int s=v.size();\n /* v = [5 7 8 5 6] Iterate V from Back\n If Element is Even Replace It With Top Of Even Queue\n If Element is Odd Replace It With Top Of Odd Queue\n */\n for(int i=s-1;i>=0;i--)\n {\n if(v[i] & 1){\n v[i]=Odd.top();\n Odd.pop();\n }\n else{\n v[i]=Even.top();\n Even.pop();\n }\n n=n*10+v[i];\n }\n return n;\n }\n\n```\n\n---\n# *Guy\'s Upvote Pleasee !!* \n![up-arrow_68804.png](https://assets.leetcode.com/users/images/05f74320-5e1a-43a6-b5cd-6395092d56c8_1719302919.2666397.png)\n\n# ***(\u02E3\u203F\u02E3 \u035C)***\n\n\n
2
0
['Sorting', 'Heap (Priority Queue)', 'C++']
0
largest-number-after-digit-swaps-by-parity
BEATS 100% CPP SOLUTION WITH LINE-BY-LINE EXPLANATION
beats-100-cpp-solution-with-line-by-line-inhu
\n\n# Approach\n It converts the given integer num to a string s to work with its individual digits.\n\n It iterates through the digits of the string s using tw
Dominating_
NORMAL
2023-09-28T09:39:35.144319+00:00
2023-09-28T09:39:35.144350+00:00
402
false
\n\n# Approach\n* It converts the given integer num to a string s to work with its individual digits.\n\n* It iterates through the digits of the string s using two nested loops. The outer loop (i) selects the current digit, and the inner loop (j) compares it with subsequent digits.\n\n* For each pair of digits (current digit and subsequent digit), it checks if they have the same even/odd status. If they do, it compares their values and swaps them if the subsequent digit is greater. This swapping ensures that the largest possible number is formed while maintaining the even/odd status of the digits.\n\nAfter processing all pairs of digits, it converts the modified string back to an integer using stoi and returns the result.\n\n\n# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num); // Convert the integer to a string to work with its digits.\n\n for (int i = 0; i < s.size(); i++) {\n bool even = (s[i] - \'0\') % 2 == 0; // Check if the current digit is even or odd.\n\n for (int j = i + 1; j < s.size(); j++) {\n // Compare the even/odd status of digits and swap them if necessary.\n if (even == ((s[j] - \'0\') % 2 == 0)) {\n if (s[i] < s[j]) {\n swap(s[i], s[j]); // Swap digits to maximize the value.\n }\n }\n }\n }\n\n return stoi(s); // Convert the string back to an integer and return the result.\n }\n};\n\n```
2
0
['C++']
0
largest-number-after-digit-swaps-by-parity
easy solution using priority queue
easy-solution-using-priority-queue-by-wt-rdx1
Intuition\n Describe your first thoughts on how to solve this problem. \n maintain priority queues for even and odd numbers, store all the even and odd digits i
wtfcoder
NORMAL
2023-06-17T15:12:11.011741+00:00
2023-06-17T15:12:11.011761+00:00
214
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n maintain priority queues for even and odd numbers, store all the even and odd digits in the number. traverse through the number and add the odd highest digit if it is odd , even highest digit if it is even. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n# Complexity\n- Time complexity:O(Nlogn) {N is number of digits in the number}\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\nPlease upvote if you find it helpful \n\n\n# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<int, vector<int>, greater<int>> odd, even; \n int n = num; \n while(n > 0){\n int temp = n%10; n /= 10; \n if(temp%2 == 0) even.push(temp); \n else odd.push(temp); \n } \n n = num; long long int val = 1, ans = 0; \n while(n > 0){\n int temp = n%10; n /= 10; \n if(temp % 2 == 0) {\n ans += val*(even.top()); even.pop(); val *=10; \n }\n else {\n ans += val*(odd.top()); odd.pop(); val *= 10; \n }\n }\n\n return ans; \n\n }\n};\n```
2
0
['Heap (Priority Queue)', 'C++']
0
largest-number-after-digit-swaps-by-parity
✅✔️Easy Implementation || Priority queue || 100% beat ✈️✈️✈️✈️✈️
easy-implementation-priority-queue-100-b-bmiw
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
ajay_1134
NORMAL
2023-06-14T13:30:44.456765+00:00
2023-06-14T13:30:44.456782+00:00
211
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```\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int>v;\n while(num){\n v.push_back(num%10);\n num /= 10;\n }\n reverse(v.begin(),v.end());\n priority_queue<int>pq1;\n priority_queue<int>pq2;\n for(auto dig : v){\n if(dig%2 == 0) pq1.push(dig);\n }\n for(auto dig : v){\n if(dig%2 == 1) pq2.push(dig);\n }\n int ans = 0;\n for(int i=0; i<v.size(); i++){\n if(v[i] % 2 == 0){\n ans = ans*10 + pq1.top();\n pq1.pop();\n }\n else{\n ans = ans*10 + pq2.top();\n pq2.pop();\n }\n }\n return ans;\n }\n};\n```
2
0
['Heap (Priority Queue)', 'C++']
0
largest-number-after-digit-swaps-by-parity
Simple Solution on Heap
simple-solution-on-heap-by-devill_05-xqth
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
devill_05
NORMAL
2023-05-21T10:33:33.151607+00:00
2023-05-21T10:33:33.151649+00:00
599
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```\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<int>e,o;\n vector<int>arr;\n while(num){\n arr.push_back(num%10);\n num/=10;\n }\n reverse(arr.begin(),arr.end());\n for(auto x:arr){\n if(x%2==0){\n e.push(x);\n }else{\n o.push(x);\n }\n }\n int ans=0;\n for(int i=0;i<arr.size();i++){\n if(arr[i]&1){\n int t=o.top();o.pop();\n arr[i]=t;\n }else{\n int t=e.top();e.pop();\n arr[i]=t;\n }\n }\n for(auto x:arr){\n ans=ans*10+x;\n }\n return ans;\n }\n};\n```
2
0
['C++']
1
largest-number-after-digit-swaps-by-parity
🚀🚀2231. Largest Number After Digit Swaps by Parity||EASY ||UNDERSTANDABLE||🚀🚀
2231-largest-number-after-digit-swaps-by-hjpo
Intuition\n\uD83D\uDCA1Find the largest number from the given number by swapping with partition.\n\n# Approach\n- seperate the number by single single digits an
saro_2003
NORMAL
2023-03-29T09:39:28.448497+00:00
2023-03-29T09:39:28.448547+00:00
2,878
false
# Intuition\n\uD83D\uDCA1Find the largest number from the given number by swapping with partition.\n\n# Approach\n- seperate the number by single single digits and store it in the array.\n- then create two vector arrays and store odd and even seperately.\n- then sort the vector odd and even arrays in descending order .\n- to sort in descending order we use greater template function.\n- then replace the first old array with the newlly update odd and even array by following steps.\n - replace odd element with odd array element.\n - replace even element with even array element.\n- then atlast convert the array elements into single number by multiple with 10 and add the current element.\n- there is small approach is needed that is normal int cannot store the largest value so that we use long long int.\n\n\n# Code\uD83E\uDDD1\uD83C\uDFFF\u200D\uD83D\uDCBB\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int>v;\n long long int temp=num;\n while(num){\n v.push_back(num%10);\n num/=10;\n }\n reverse(v.begin(),v.end());\n vector<int>v1;\n vector<int>v2;\n for(int i=0;i<v.size();i++){\n if(v[i]%2==0){\n v1.push_back(v[i]);\n }\n else{\n v2.push_back(v[i]);\n }\n }\n sort(v1.begin(),v1.end(),greater<int>());\n sort(v2.begin(),v2.end(),greater<int>());\n int k=0;\n int c=0;\n for(int i=0;i<v.size();i++){\n if(v[i]%2==0){\n v[i]=v1[k++];\n }\n else{\n v[i]=v2[c++];\n }\n }\n temp=0;\n for(int i=0;i<v.size();i++){\n temp=temp+v[i];\n temp=temp*10;\n }\n return temp/10;\n }\n};\n```\n\uD83D\uDD25SARAVANAN-2003
2
0
['C', 'Sorting', 'Heap (Priority Queue)', 'C++', 'Java']
0
largest-number-after-digit-swaps-by-parity
using heap concept python3
using-heap-concept-python3-by-mohammad_t-qq3w
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
Mohammad_tanveer
NORMAL
2023-03-19T12:25:20.101345+00:00
2023-03-19T12:25:20.101380+00:00
892
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```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n even = []\n odd = []\n res=[]\n cstr = str(num)\n for i in cstr:\n if int(i) % 2 == 0:\n even.append(-int(i))\n else:\n odd.append(-int(i))\n heapq.heapify(even)\n heapq.heapify(odd)\n for value in cstr:\n val=int(value)\n if val%2==0:\n res.append(str(-heapq.heappop(even)))\n else:\n res.append(str(-heapq.heappop(odd)))\n return int("".join(res))\n```
2
0
['Heap (Priority Queue)', 'Python3']
0
largest-number-after-digit-swaps-by-parity
max heap || easy
max-heap-easy-by-2stellon7-7pv9
\n\n# Code\n\nclass Solution:\n def largestInteger(self, num: int) -> int:\n evenlist=[]\n oddlist=[]\n nums= [int(x) for x in str(num)]
2stellon7
NORMAL
2022-12-27T18:44:10.843481+00:00
2022-12-27T18:44:10.843515+00:00
2,759
false
\n\n# Code\n```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n evenlist=[]\n oddlist=[]\n nums= [int(x) for x in str(num)]\n for i in nums:\n if i%2==0:\n evenlist.append(i)\n else:\n oddlist.append(i)\n even= [-x for x in evenlist]\n odd = [-x for x in oddlist]\n heapq.heapify(even)\n heapq.heapify(odd)\n result=[]\n for ele in nums:\n if ele in evenlist:\n result+=[-heapq.heappop(even)]\n if ele in oddlist:\n result+=[-heapq.heappop(odd)]\n result =[str(x) for x in result] \n return int(\'\'.join(result))\n\n\n \n\n\n \n\n\n```
2
0
['Python3']
0
largest-number-after-digit-swaps-by-parity
C++ Solution
c-solution-by-pranto1209-xwse
Code\n\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<char> q0, q1;\n string s = to_string(num);\n int vis[
pranto1209
NORMAL
2022-12-01T17:28:18.853163+00:00
2023-04-01T18:13:50.328995+00:00
1,152
false
# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<char> q0, q1;\n string s = to_string(num);\n int vis[15] = {};\n for(int i=0; i<s.size(); i++) {\n if((s[i]-\'0\') % 2) q1.push(s[i]), vis[i] = 1;\n else q0.push(s[i]);\n }\n string t;\n for(int i=0; i<s.size(); i++) {\n if(vis[i]) t.push_back(q1.top()), q1.pop();\n else t.push_back(q0.top()), q0.pop();\n }\n int ans = stoi(t);\n return ans;\n }\n};\n```
2
0
['C++']
0
largest-number-after-digit-swaps-by-parity
WORST SOLUTION | JAVA | BASIC
worst-solution-java-basic-by-prathmeshde-hk95
Intuition\n Describe your first thoughts on how to solve this problem. \nused string and list to store the even and odd elements\n\n# Approach\n Describe your a
prathmeshdeshpande101
NORMAL
2022-11-25T11:01:15.908128+00:00
2022-11-25T11:01:15.908176+00:00
1,363
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nused string and list to store the even and odd elements\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nconverted num in string then added all values from string to even and odd list as per its type;\nthen sorted both string in desc order\nas we check from the original string if got even number we will put max even number from even list and incresed even list pointer same for the odd number\n\nConverted result string to integer to get int res and returned it\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```\nclass Solution {\n public int largestInteger(int num) {\n String numString = ""+ num;\n List<Integer> even = new ArrayList<>();\n List<Integer> odd = new ArrayList<>();\n for(Character c : numString.toCharArray()){\n int n = Character.getNumericValue(c);\n if(n%2==0){\n even.add(n);\n }else{\n odd.add(n);\n }\n }\n Collections.sort(even, Collections.reverseOrder());\n Collections.sort(odd, Collections.reverseOrder());\n String res ="";\n int one=0, two=0;\n for(int i=0; i<numString.length(); i++){\n int n = Character.getNumericValue(numString.charAt(i));\n if(n%2==0){\n res += even.get(one);\n one++;\n }else{\n res += odd.get(two);\n two++;\n }\n }\n return Integer.parseInt(res);\n }\n}\n```
2
0
['Java']
0
largest-number-after-digit-swaps-by-parity
Largest Number After Digit Swaps by Parity Solution Java
largest-number-after-digit-swaps-by-pari-wsc1
class Solution {\n public int largestInteger(int num) {\n final String s = String.valueOf(num);\n int ans = 0;\n // maxHeap[0] := odd digits\n // m
bhupendra786
NORMAL
2022-08-16T08:16:07.494147+00:00
2022-08-16T08:16:07.494193+00:00
239
false
class Solution {\n public int largestInteger(int num) {\n final String s = String.valueOf(num);\n int ans = 0;\n // maxHeap[0] := odd digits\n // maxHeap[1] := even digits\n Queue<Integer>[] maxHeap = new Queue[2];\n\n for (int i = 0; i < 2; ++i)\n maxHeap[i] = new PriorityQueue<>(Comparator.reverseOrder());\n\n for (final char c : s.toCharArray()) {\n final int digit = c - \'0\';\n maxHeap[digit & 1].offer(digit);\n }\n\n for (final char c : s.toCharArray()) {\n final int i = c - \'0\' & 1;\n ans = (ans * 10 + maxHeap[i].poll());\n }\n\n return ans;\n }\n}\n
2
0
['Heap (Priority Queue)']
0
largest-number-after-digit-swaps-by-parity
Simple c++ solution | 100% faster | O(n)
simple-c-solution-100-faster-on-by-pravi-5fhh
Sorting is done for atmost 9 digits so its constant O(9 log9), for both time and space.\nOverall complexity: time - O(n), space - (1)\n\n1. Separate digits as p
pravin_ar
NORMAL
2022-07-22T09:17:08.234489+00:00
2022-07-22T09:17:08.234534+00:00
217
false
Sorting is done for atmost 9 digits so its constant O(9 log9), for both time and space.\nOverall complexity: time - O(n), space - (1)\n\n1. Separate digits as per parity.(odd/even)\n2. Sort individual odd & even array of digits\n3. Create num again using odd even array as per parity\n4. Note that we are using decending order of odd even to create max num. \n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n int o[10], e[10], s[10];\n int i = 0, j = 0;\n while(num) {\n int c = num%10; num /= 10;\n if(1&c) o[i++] = c;\n else e[j++] = c;\n s[i+j-1] = c;\n }\n sort(o, o+i);\n sort(e, e+j);\n for(int d = i+j-1; d >= 0; --d) {\n if(1&s[d]) num = num*10 + o[--i];\n else num = num*10 + e[--j];\n }\n return num;\n }\n};\n```\n\nSame solution can be implemented using string.\n\nThis is smaller case where digits are max 9.\nIncase where digits are large( >10^4), space can be reduced by using char array (1 Byte) instead of int (4 Bytes).\n\nHere\'s string implementation:\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num), res = "";\n char o[10], e[10];\n int i = 0, j = 0;\n for(char c: s) {\n if(1&c) o[i++] = c;\n else e[j++] = c;\n }\n sort(o, o+i);\n sort(e, e+j);\n for(char c: s) {\n if(1&c) res += o[--i];\n else res += e[--j];\n }\n num = stoi(res);\n return num;\n }\n};\n```
2
0
['Sorting']
0
largest-number-after-digit-swaps-by-parity
C++ || 0ms || using 2 priority queues
c-0ms-using-2-priority-queues-by-shivavi-7ies
Hello folks!... Here our question is to find the largest possible number after swapping numbers with same parity.\n\nSuppose our number is 1234 (say num), \n\nH
ShivaVishwakarma
NORMAL
2022-06-24T11:12:15.982701+00:00
2022-07-08T10:36:06.421114+00:00
215
false
Hello folks!... Here our question is to find the **largest** possible number after swapping numbers with **same parity**.\n\nSuppose our number is **1234** (say **num**), \n\nHere we will make **2 max priority queues**, one is **odd priority queue** and other is **even priority queue**.\nNow, we will push all the even digits of num in even priority and odd digits in odd priority queue.\n\n**So how to do so????**\n\nWe will check each and every single digit number from num. To do so, we have learned a trick if you remember!...\nWe will keep doing **modulo of number by 10** to receive unit digit of a number, store it and then **divide number by 10** to get all the remaining digits of num.\n\n**Confusing?????**\n\n**Let me help you!...**\n1. num = 1234\n2. int d = num % 10 (so we will have d = 4)\n3. now we received one digit, so we do \n num /= 10 (via this, num will be 123)\n4. now we will follow step 2 and 3 till num becomes 0, then we stop.\n\nNow exactly same approach we will use here.\nWe will store all the **even digits in evenPriority and odd digits in oddPriority**.\n\nAnd yeah, **make sure to keep copy of original num (i.e. 1234) in string format** (you will know later why in string), because this process, your num will become 0.\n\nSo our priority queue status will be right now is,\n**Even Priority Queue : 2, 4 (4 is on top of evenpq)**\n**Odd Priority Queue: 1, 3 (3 is on top of oddpq)**\n\nNow, the main question begins... We need to swap the digits to make it larger possible number.\nNow here we require our number in string format.\nBecause, if we have our number in int format, we won\'t access 1st digit directly (**If you know any way to reach 1st digit directly then please let me know**).\n\nSo now, we will run a loop in that number string and checks every char of string to be even or odd.\n**If it is even**, then we will **replace it by evenPriority Queue top value** and then we will **pop out evenPriority Queue top value**.\n**If it is odd**, then we will **replace it by oddPriority Queue top value** and then we will **pop out oddPriority Queue top value**. \n\nIn this way, you will recieve your **correct ans in string format**. But our function is of int type...... Hmmm.... So what we can do????\n\nWe will simply use **inbuilt function stoi()**, which will convert our string to int and then you need to return that value and you are done here.\n\n```\nint largestInteger(int num) {\n\tpriority_queue<int> evenpq;\n\tpriority_queue<int> oddpq;\n\tstring n = to_string(num);\n\n\tdo{\n\t\tint d = num%10;\n\t\tif(d%2 == 0)\n\t\t\tevenpq.push(d);\n\n\t\telse\n\t\t\toddpq.push(d);\n\n\t\tnum /= 10;\n\t}while(num != 0);\n\n\tfor(int i=0; i<n.size(); i++)\n\t{\n\t\tint x = n[i] - \'0\';\n\t\tif(x%2 == 0)\n\t\t{\n\t\t\tchar ch = evenpq.top() + \'0\';\n\t\t\tn[i] = ch;\n\t\t\tevenpq.pop();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tchar ch = oddpq.top() + \'0\';\n\t\t\tn[i] = ch;\n\t\t\toddpq.pop();\n\t\t}\n\t}\n\n\treturn stoi(n);\n}\n```\n\nI hope my solution is easy to understand for you. Please **UPVOTE** it if you found it useful
2
0
['Heap (Priority Queue)']
0
largest-number-after-digit-swaps-by-parity
Using two priority queue JAVA
using-two-priority-queue-java-by-user586-n2ak
\n\npublic int largestInteger(int num) {\n\t\tPriorityQueue<Integer> evenPq = new PriorityQueue<>();\n\t\tPriorityQueue<Integer> oddPq = new PriorityQueue<>();\
user5869CS
NORMAL
2022-05-29T15:57:38.876779+00:00
2022-05-29T15:57:38.876860+00:00
410
false
```\n\npublic int largestInteger(int num) {\n\t\tPriorityQueue<Integer> evenPq = new PriorityQueue<>();\n\t\tPriorityQueue<Integer> oddPq = new PriorityQueue<>();\n\t\tint ref = num;\n\t\twhile ( num > 0 ) {\n\t\t\tint right = num % 10;\n\t\t\tif ( right % 2 == 1 ) {\n\t\t\t\toddPq.offer(right);\n\t\t\t} else {\n\t\t\t\tevenPq.offer(right);\n\t\t\t}\n\t\t\tnum /= 10;\n\t\t}\n\t\tint num2 = 0;\n int mul = 1;\n \n\t\twhile ( ref > 0 ) {\n int cur = ref % 10;\n\t\t\tif ( cur % 2 == 1 ) {\n\t\t\t\tnum2 = oddPq.poll() * mul + num2;\n\t\t\t} else {\n num2 = evenPq.poll() * mul + num2;\n\t\t\t}\n\t\t\tref /= 10;\n mul *= 10;\n\t\t}\n\t\treturn num2;\n }\n\t\n\t\n```
2
0
['Heap (Priority Queue)', 'Java']
0
largest-number-after-digit-swaps-by-parity
Wrong Testcase (Solved)
wrong-testcase-solved-by-alfinm01-8667
Answer: Apparently the testcase isn\'t wrong, the misunderstanding has been explained by UserASh at https://leetcode.com/problems/largest-number-after-digit-swa
alfinm01
NORMAL
2022-04-23T16:15:02.344173+00:00
2022-06-19T13:19:20.794084+00:00
231
false
***Answer**: Apparently the testcase isn\'t wrong, the misunderstanding has been explained by UserASh at https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1975735/Wrong-Testcase/1367969*\n\n-----------------------------------------\n\n**Wrong Testcase:**\nThe expected answer should be `742` thus my answer should be correct\n![image](https://assets.leetcode.com/users/images/7efe0ca4-f2b0-4d84-9387-2efc528b2557_1650730266.2291672.png)\n\n**My Code:**\n```golang\ntype Digit struct {\n Value int\n Index int\n}\n\nfunc largestInteger(num int) int {\n result := 0\n digits := make([]int, 0)\n maxParity1 := Digit{\n Value: -1,\n Index: -1,\n }\n maxParity2 := Digit{\n Value: -1,\n Index: -1,\n }\n \n i := 0\n firstParity := true\n for n := num; n > 0; n /= 10 {\n digit := n % 10\n digits = prependInt(digits, digit)\n if firstParity {\n if digit > maxParity1.Value {\n maxParity1.Value = digit\n maxParity1.Index = i\n }\n } else {\n if digit > maxParity2.Value {\n maxParity2.Value = digit\n maxParity2.Index = i\n }\n }\n i++\n firstParity = !firstParity\n }\n \n if len(digits)%2 == 0 {\n maxParity1, maxParity2 = maxParity2, maxParity1\n }\n \n for i := 0; i < len(digits); i += 2 {\n if digits[i] <= maxParity1.Value {\n digits[i], digits[len(digits)-1-maxParity1.Index] = maxParity1.Value, digits[i]\n break\n }\n }\n \n for i := 1; i < len(digits); i += 2 {\n if digits[i] <= maxParity2.Value {\n digits[i], digits[len(digits)-1-maxParity2.Index] = maxParity2.Value, digits[i]\n break\n }\n }\n \n for _, digit := range digits {\n result = result*10 + digit\n }\n \n return result\n}\n\nfunc prependInt(x []int, y int) []int {\n x = append(x, 0)\n copy(x[1:], x)\n x[0] = y\n \n return x\n}\n```\n\n**Local Accepted Testcases:**\n```\n// Input\n1234\n65875\n1\n2\n10\n11\n123456\n654321\n999999888\n999999988\n999999998\n999999999\n1000000000\n```\n```\n// Output\n3412\n87655\n1\n2\n10\n11\n563412\n654321\n999999888\n999999988\n999999998\n999999999\n1000000000\n```
2
0
['Go']
2
largest-number-after-digit-swaps-by-parity
C++, Easy to understand, Faster than 100%, Priority Queue
c-easy-to-understand-faster-than-100-pri-fehq
```\n int largestInteger(int num) {\n priority_queuepq1;\n priority_queuepq2;\n \n string s=to_string(num);\n int i=0;\n
msk318809
NORMAL
2022-04-17T07:02:12.630104+00:00
2022-06-25T18:41:15.901100+00:00
193
false
```\n int largestInteger(int num) {\n priority_queue<int>pq1;\n priority_queue<int>pq2;\n \n string s=to_string(num);\n int i=0;\n int n=s.size();\n while(n)\n { if(s[i]%2!=0)\n pq1.push(s[i]);\n else\n pq2.push(s[i]);\n i++;\n n--;\n }\n i=0;\n string ans;\n while(!pq1.empty()||!pq2.empty())\n {\n if(s[i]%2!=0){\n ans+=pq1.top(); pq1.pop();}\n else{\n ans+=pq2.top();pq2.pop();}\n i++;\n }\n \n return stoi(ans);\n\t\t}\n\t\t\n\t\t
2
0
['C', 'Heap (Priority Queue)']
0
largest-number-after-digit-swaps-by-parity
[Python3] 5 lines. Sort odd and even numbers
python3-5-lines-sort-odd-and-even-number-bpe6
If the first number is an odd number, to make the total number biggest, we need to swap the biggest odd number to this place. If the first number is even number
yuanzhi247012
NORMAL
2022-04-13T01:41:59.839590+00:00
2022-04-13T10:00:52.999371+00:00
199
false
If the first number is an odd number, to make the total number biggest, we need to swap the biggest odd number to this place. If the first number is even number, we swap the biggest even number to this place.\nFor the second number, if it is odd, we swap the 2nd biggest odd number to this place. If it is even, we swap the 2nd biggest even number to this place.\nWe can put all the odd numbers and even number into 2 sorted lists, and place them back to the original number in a big to small order.\n```\n def largestInteger(self, num: int) -> int:\n digits = [int(d) for d in str(num)]\n odd = sorted([d for d in digits if d%2 == 1])\n even = sorted([d for d in digits if d%2 == 0])\n resDigits =[even.pop() if digits[i]%2==0 else odd.pop() for i in range(len(digits))]\n return int(\'\'.join([str(d) for d in resDigits]))\n```
2
0
[]
2
largest-number-after-digit-swaps-by-parity
C++ Simple Approach || Sorting || Easy
c-simple-approach-sorting-easy-by-yogesh-siq5
\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s=to_string(num);\n string a,b;\n for(char c:s){\n if(c%2==0
Yogesh02
NORMAL
2022-04-11T14:56:16.561682+00:00
2022-04-11T14:56:16.561715+00:00
383
false
```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s=to_string(num);\n string a,b;\n for(char c:s){\n if(c%2==0){\n a+=c;\n }\n else{\n b+=c;\n }\n }\n sort(a.begin(),a.end(),greater<int>());\n sort(b.begin(),b.end(),greater<int>());\n int i=0,j=0;\n for(int k=0;k<s.size();k++){\n if(s[k]%2==0){\n s[k]=a[i];\n i++; \n }\n else{\n s[k]=b[j];\n j++;\n }\n }\n return stoi(s);\n }\n};\n```
2
0
['C', 'Sorting', 'C++']
0
largest-number-after-digit-swaps-by-parity
[JavaScript] Simple, Clean NlogN Sorting Solution
javascript-simple-clean-nlogn-sorting-so-hqxs
\n/*\n1. Seperate even and odd values into seperate arrays\n2. Sort both in ascending order (that way popping from the end will give max even or add number in O
YogiPaturu
NORMAL
2022-04-10T14:53:23.488170+00:00
2022-04-10T14:53:23.488214+00:00
620
false
```\n/*\n1. Seperate even and odd values into seperate arrays\n2. Sort both in ascending order (that way popping from the end will give max even or add number in O(1) time)\n3. Loop through nums\n - If it\'s an even number, pop from the even array (i.e., the largest even number)\n - Otherwise, it\'s an odd number, pop from the odd array (i.e., the largest odd number)\n4. Return the largestNum array joined\n\nTime: n + nlogn + nlogn + n = 2n + 2nlogn = nlogn\nSpace: 4n = n\n*/\nvar largestInteger = function(num) {\n const odd = [];\n const even = [];\n const nums = String(num).split(\'\')\n \n for(let i = 0; i < nums.length; i++){\n if(nums[i] % 2 === 0) even.push(parseInt(nums[i]))\n else odd.push(parseInt(nums[i]))\n }\n \n odd.sort((a,b) => a-b)\n even.sort((a,b) => a-b)\n \n const largestNum = [];\n for(let i = 0; i < nums.length; i++){\n if(nums[i] % 2 === 0) largestNum.push(even.pop())\n else largestNum.push(odd.pop())\n }\n\n return largestNum.join(\'\')\n};\n```
2
0
['Sorting', 'JavaScript']
1
largest-number-after-digit-swaps-by-parity
C++ | | EASY TO UNDERSTAND
c-easy-to-understand-by-pratik263-mc0p
\n\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n int n = s.size();\n for(int i=0; i<n; i++){
pratik263
NORMAL
2022-04-10T10:22:47.530461+00:00
2022-04-10T10:22:47.530489+00:00
62
false
\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n int n = s.size();\n for(int i=0; i<n; i++){\n for(int j=i+1; j<n; j++){\n int b = (s[j] - \'0\');\n int p = (s[i] - \'0\');\n if(p<b && ((p%2==0 && b%2==0 && b!=0) || (p%2 && b%2))){\n swap(s[i],s[j]);\n }\n }\n }\n int ans = stoi(s);\n return ans;\n }\n};\n```
2
0
['String', 'Sorting']
0
largest-number-after-digit-swaps-by-parity
simple c++ solution
simple-c-solution-by-crybaby_01-ij9v
\nint largestInteger(int num) {\n string s=to_string(num);\n int n=s.size();\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n
Crybaby_01
NORMAL
2022-04-10T07:43:09.633966+00:00
2022-04-10T07:43:09.633998+00:00
69
false
```\nint largestInteger(int num) {\n string s=to_string(num);\n int n=s.size();\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n if((s[i]-\'0\')%2==0&&(s[j]-\'0\')%2==0&&s[i]<s[j]) swap(s[i],s[j]); //both even\n else if((s[i]-\'0\')%2!=0&&(s[j]-\'0\')%2!=0&&s[i]<s[j]) swap(s[i],s[j]); // both odd\n }\n }\n return stol(s);\n }\n```
2
0
['String', 'C']
0
largest-number-after-digit-swaps-by-parity
✔️ 2 solution approaches explained with logic and code || 8ms || 2ms || beats 100%
2-solution-approaches-explained-with-log-jn6b
Solution 1 Idea : If swapping is allowed among odd numbers or even numbers, then why not construct a list of all odd numbers and even numbers and sort them in d
pg07codes
NORMAL
2022-04-10T04:40:45.197424+00:00
2022-04-10T04:40:45.197453+00:00
263
false
**Solution 1 Idea** : If swapping is allowed among odd numbers or even numbers, then why not construct a list of all odd numbers and even numbers and sort them in descending order. Now as we go through the input number, we check if the digit is odd, we get the best from odd, increment it. If the digit is even, we get the best from even, increment it. And so on.\n\nCode will make it more clear - \n\n```\npublic int largestInteger(int n) {\n List<Integer>odds=new ArrayList<>();\n List<Integer>evens=new ArrayList<>();\n \n String[] digits = String.valueOf(n).split("");\n boolean isOdd=((digits.length&1)==1);\n for(int i=0;i<digits.length;i++){\n int d = Integer.valueOf(digits[i]);\n if((d&1)==0)\n evens.add(d);\n else\n odds.add(d);\n }\n \n Collections.sort(odds,Comparator.reverseOrder()); // sorting evens and odds as only they can be swapped\n Collections.sort(evens,Comparator.reverseOrder());\n\t\t\n int num=0; // using maths to construct this. // -> num*10+digit;\n int o=0,e=0;\n for(int i=0;i<digits.length;i++){\n if((Integer.valueOf(digits[i])&1)==0){ // if original digit was even\n num*=10;\n num+=evens.get(e); // get the best from even and increment it\n e++;\n }else{ // if original digit was even\n num*=10;\n num+=odds.get(o); // get the best from odd and increment it\n o++;\n }\n }\n \n return num;\n \n }\n```\n\nFor this approach, space complexity is O(2n), time complexity is O(nlogn). For the next solution, the time complexity is more but it is much more cleaner, faster(*yes, in practice, below one runs faster*)and short).\n\n**Solution 2 Idea** : The idea is to go over all the digit one by one and get the best for that place from its right and swap it with that value. The commented code will make the idea clear.\n\n ```\npublic int largestInteger(int n){\n char[] digits = String.valueOf(n).toCharArray();\n for(int i = 0; i < digits.length; i++) // i denotes the digit for which we will try to get the best from right side\n for(int j = i + 1; j < digits.length; j++) // looping over right side from [i+1..end]\n if(digits[j] > digits[i] && (digits[j] - digits[i]) % 2 == 0){ // if number is larger than a[i] and of same parity\n char temp = digits[i];\n digits[i] = digits[j];\n digits[j] = temp;\n }\n return Integer.parseInt(new String(digits));\n }\n```\n\n**Here the space complexity is O(n) and time complexity is O(n^2)**\n\nPlease do upvote if you found it useful. Thanks.
2
0
['Java']
0
largest-number-after-digit-swaps-by-parity
Python heap
python-heap-by-nuoaleon-58s4
\nclass Solution:\n def largestInteger(self, num: int) -> int:\n \n arr = list(str(num))\n \n odd = []\n even = []\n
Nuoaleon
NORMAL
2022-04-10T04:29:53.592209+00:00
2022-04-10T04:30:36.174705+00:00
106
false
```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n \n arr = list(str(num))\n \n odd = []\n even = []\n \n for ch in arr:\n if int(ch)%2 == 0:\n even.append(-int(ch))\n else:\n odd.append(-int(ch))\n \n heapq.heapify(odd)\n heapq.heapify(even)\n \n \n ans = []\n for ch in arr:\n if int(ch)%2 == 0:\n ans.append(-heapq.heappop(even))\n else:\n ans.append(-heapq.heappop(odd))\n \n return "".join(map(str,ans))\n```
2
0
['Greedy', 'Heap (Priority Queue)']
0
largest-number-after-digit-swaps-by-parity
Python | Priority Queue Solution | O(n log n)
python-priority-queue-solution-on-log-n-p37f8
Approach :\n\n Store odd/even for each position.\n Use 2 priority queues to record the numbers of odd/even.\n* For each position, add the biggest number from od
phondani0
NORMAL
2022-04-10T04:29:16.133721+00:00
2022-04-10T04:36:05.002091+00:00
332
false
**Approach :**\n\n* Store odd/even for each position.\n* Use 2 priority queues to record the numbers of odd/even.\n* For each position, add the biggest number from odd/even priority_queue to ans.\n```\nfrom queue import PriorityQueue\n\nclass Solution:\n def largestInteger(self, num: int) -> int:\n arr = []\n arr.extend(str(num))\n arr = list(map(int, arr))\n pq1 = PriorityQueue()\n pq2 = PriorityQueue()\n \n for i in range(len(arr)):\n if(arr[i] % 2 == 0):\n\t\t\t\t# Converting min heap to max heap\n pq1.put((-1*arr[i], i))\n else:\n pq2.put((-1*arr[i], i))\n \n ans = []\n \n for i in range(len(arr)):\n \n if(arr[i] % 2 == 0):\n index = pq1.get()[1]\n ans.append(arr[index])\n \n else:\n index = pq2.get()[1]\n ans.append(arr[index])\n \n \n return "".join(map(str, ans))\n```\n\nTime Complexity: O(n log n)\n\n
2
0
['Heap (Priority Queue)', 'Python']
0
largest-number-after-digit-swaps-by-parity
C++ || Easy Brute Force || swap odd and even
c-easy-brute-force-swap-odd-and-even-by-ov40w
```\nint largestInteger(int num) {\n string n=to_string(num);\n for(int i=0;in[i])\n {\n swap(n[i],n[j]);\n }\n
Aanchal20
NORMAL
2022-04-10T04:12:34.221884+00:00
2022-04-10T04:12:34.221916+00:00
65
false
```\nint largestInteger(int num) {\n string n=to_string(num);\n for(int i=0;i<n.size();i++)\n {\n for(int j=i+1;j<n.size();j++)\n {\n if(n[i]%2==0)\n {\n if(n[j]%2==0 && n[j]>n[i])\n {\n swap(n[i],n[j]);\n }\n }\n else\n {\n if(n[j]%2!=0 && n[j]>n[i])\n {\n swap(n[i],n[j]);\n }\n }\n }\n }\n return stoi(n);\n }
2
0
[]
0
largest-number-after-digit-swaps-by-parity
c++ | easy to understanding
c-easy-to-understanding-by-smit3901-r2ec
\n\tint largestInteger(int num) {\n string s = to_string(num);\n \n for(int i=0;i < s.size();i++)\n {\n for(int j=i+1;j <
smit3901
NORMAL
2022-04-10T04:01:57.030051+00:00
2022-04-10T04:01:57.030111+00:00
201
false
\n\tint largestInteger(int num) {\n string s = to_string(num);\n \n for(int i=0;i < s.size();i++)\n {\n for(int j=i+1;j < s.size();j++)\n {\n if(s[i] < s[j] and ((s[i] - \'0\') % 2) == ((s[j] - \'0\') % 2))\n {\n char c = s[i];\n s[i] = s[j];\n s[j] = c;\n }\n }\n }\n return stoi(s);\n }\n
2
0
['C']
1
largest-number-after-digit-swaps-by-parity
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-pari-itmk
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n log n)Code
Vinil07
NORMAL
2025-03-30T17:44:17.620486+00:00
2025-03-30T17:44:17.620486+00:00
58
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n log n) # Code ```cpp [] class Solution { public: int largestInteger(int num) { string nums=to_string(num); vector<int>odd,even; for(char c:nums) { if((c-'0')%2==0){ even.push_back(c-'0'); } else{ odd.push_back(c-'0'); } } sort(even.rbegin(),even.rend()); sort(odd.rbegin(),odd.rend()); int oddindex=0,evenindex=0; for(char &c:nums){ if((c-'0')%2==1){ c=odd[oddindex++]+'0'; } else{ c=even[evenindex++]+'0'; } } return stoi(nums); } }; ```
1
0
['C++']
0
largest-number-after-digit-swaps-by-parity
Beats 100% in both Space Complexity and Time Complexity
beats-100-in-both-space-complexity-and-t-gwqt
IntuitionApproachComplexity Time complexity: Space complexity: Code
eshaansingla
NORMAL
2025-03-29T13:15:25.256092+00:00
2025-03-29T13:15:25.256092+00:00
19
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int largestInteger(int num) { vector<int>even,odd,nums; int s=0; while(num){ if(num%10%2) odd.emplace_back(num%10); else even.emplace_back(num%10); nums.emplace_back(num%10); num/=10; s++; } sort(odd.begin(),odd.end()); sort(even.begin(),even.end()); int ans=0; vector<int>solver(s); int i=0; int j=0; int k=0; while(s--){ if(nums[i]%2){ solver[i]=(odd[j++]); } else{ solver[i]=(even[k++]); } i++; } for(int i=solver.size()-1;i>=0;i--){ ans=ans*10+solver[i]; } return ans; } }; ```
1
0
['Sorting', 'C++']
0
largest-number-after-digit-swaps-by-parity
Easy Java Solution
easy-java-solution-by-vermaanshul975-qkly
IntuitionApproachComplexity Time complexity: Space complexity: Code
vermaanshul975
NORMAL
2025-03-27T14:57:45.839590+00:00
2025-03-27T14:57:45.839590+00:00
122
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] import java.util.*; class Solution { public int largestInteger(int num) { char[] str = Integer.toString(num).toCharArray(); List<Character> odd = new ArrayList<>(); List<Character> even = new ArrayList<>(); for (char s : str) { if ((s - '0') % 2 == 0) { even.add(s); } else { odd.add(s); } } odd.sort(Collections.reverseOrder()); even.sort(Collections.reverseOrder()); StringBuilder res = new StringBuilder(); int oddIndex = 0, evenIndex = 0; for (char s : str) { if ((s - '0') % 2 == 0) { res.append(even.get(evenIndex++)); } else { res.append(odd.get(oddIndex++)); } } return Integer.parseInt(res.toString()); } } ```
1
0
['Java']
0
largest-number-after-digit-swaps-by-parity
Extract odd/even digits
extract-oddeven-digits-by-linda2024-ssh9
IntuitionApproachComplexity Time complexity: Space complexity: Code
linda2024
NORMAL
2025-02-06T20:37:05.274553+00:00
2025-02-06T20:37:05.274553+00:00
15
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```csharp [] public class Solution { public int LargestInteger(int num) { List<int> odds = new(), evens = new(); int cur = num; while(cur > 0) { int rest = cur%10; if(rest%2 == 0) evens.Add(rest); else odds.Add(rest); cur /= 10; } int digits = 1; odds.Sort(); evens.Sort(); int idxOdd = 0, idxEven =0; int res = 0; cur = num; while(cur > 0) { int rest = cur %10; int val = rest%2 == 0 ? evens[idxEven++] : odds[idxOdd++]; res += (val*digits); digits *= 10; cur /= 10; } return res; } } ```
1
0
['C#']
0
largest-number-after-digit-swaps-by-parity
C++ O(log(n)) digit extraction
c-ologn-digit-extraction-by-vdrizzle-bxnu
IntuitionExtract the count of the digits from num O(log10​(n)) Then built a new int based on the parity of digits in num from left to rightApproachFirst you ext
vdrizzle
NORMAL
2025-01-30T06:23:35.762700+00:00
2025-01-30T06:23:35.762700+00:00
179
false
# Intuition Extract the count of the digits from `num` $$O(log_{10}(n))$$ Then built a new int based on the parity of digits in `num` from left to right <!-- Describe your first thoughts on how to solve this problem. --> # Approach First you extract all the digits from `num` and track the count of their appearence, this runtime is O(logn). Then you iterate the digits of `num` from left to right and add the largest counted digit that has the same parity as this extracted digit. Iterating the digits form left to right is also $$O(logn)$$. LeetCode analyzed this as having a runtime complexity of $$O(n)$$ but it should be $$O(logn)$$ since the number of digits in an integer is $$log_{10}(n)$$ and the digits are are only used once per loop <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: $$O(log(n))$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int largestInteger(const int num) { std::array<int, 10> digits = {0}; // extract the count of digits int numCpy = num; while (numCpy != 0) { const int digit = numCpy % 10; numCpy /= 10; ++digits[digit]; } // copy num again numCpy = num; // Find the highest place value to help get 'num' digits from left to right int divisor = 1; while (num / divisor >= 10) { divisor *= 10; } int evenIdx = 8; int oddIdx = 9; int ret = 0; // put the digits in order based on 'num' digits from left to right while (divisor > 0) { const int digit = numCpy / divisor; numCpy %= divisor; divisor /= 10; if (digit % 2 == 0) { // find the even digit to add while (evenIdx >= 0 && digits[evenIdx] == 0) { evenIdx -= 2; } ret = ret * 10 + evenIdx; --digits[evenIdx]; } else { // find the even digit to add while (oddIdx >= 0 && digits[oddIdx] == 0) { oddIdx -= 2; } ret = ret * 10 + oddIdx; --digits[oddIdx]; } } return ret; } }; ```
1
0
['C++']
0
largest-number-after-digit-swaps-by-parity
JavaScript | Simple intuitive approach
javascript-simple-intuitive-approach-by-7q0rr
Approach Get all odd digits and sort them in increasing order. Get all even digits and sort them in increasing order. Go through all the digits: if it's even, t
dsitdikov
NORMAL
2025-01-18T16:50:45.988751+00:00
2025-01-18T16:50:45.988751+00:00
38
false
# Approach 1. Get all odd digits and sort them in increasing order. 2. Get all even digits and sort them in increasing order. 3. Go through all the digits: if it's even, take the last from the even stack and push to result; otherwise, from the odd stack. # Complexity - Time complexity: O(NlogN) - Space complexity: O(N) # Code ```javascript [] /** * @param {number} num * @return {number} */ var largestInteger = function(num) { const result = [] const digits = String(num).split('') const odds = digits.filter((num) => num % 2 !== 0).sort((a, b) => a - b) const evens = digits.filter((num) => num % 2 === 0).sort((a, b) => a - b) for (let i = 0; i < digits.length; i++) { if (digits[i] % 2 === 0) { result.push(evens.pop()) } else { result.push(odds.pop()) } } return Number(result.join('')) }; ```
1
0
['JavaScript']
0
largest-number-after-digit-swaps-by-parity
Dart Solution
dart-solution-by-abiinavvv-gqfy
IntuitionApproachComplexity Time complexity: Space complexity: Code
abiinavvv
NORMAL
2025-01-04T08:57:27.031274+00:00
2025-01-04T08:57:27.031274+00:00
10
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```dart [] class Solution { int largestInteger(int num) { final input = num.toString().split('').map((e) => int.parse(e)).toList(); final evenList = <int>[]; final oddList = <int>[]; for (var i = 0; i < input.length; i++) { input[i].isEven ? evenList.add(input[i]) : oddList.add(input[i]); } evenList.sort(); oddList.sort(); var result = ''; for (var i = 0; i < input.length; i++) { input[i].isEven ? result += '${evenList.removeLast()}' : result += '${oddList.removeLast()}'; } return int.parse(result); } } ```
1
0
['Sorting', 'Heap (Priority Queue)', 'Dart']
0
largest-number-after-digit-swaps-by-parity
🟢🔴🟢 Beats 100.00%👏 Easiest Solution 🟢🔴🟢
beats-10000-easiest-solution-by-develope-nr50
\nclass Solution {\n int largestInteger(int num) {\n List<int> digits = [];\n while(num != 0){\n int r = num % 10;\n num ~/= 10;\n d
developerSajib88
NORMAL
2024-10-28T16:35:42.541219+00:00
2024-10-28T16:35:42.541241+00:00
116
false
```\nclass Solution {\n int largestInteger(int num) {\n List<int> digits = [];\n while(num != 0){\n int r = num % 10;\n num ~/= 10;\n digits.add(r);\n }\n digits = digits.reversed.toList();\n int largest = int.parse(digits.join());\n for(int i = 0; i < digits.length; i++){\n for(int j = i+1; j < digits.length; j++){\n if(\n (digits[i].isEven && digits[j].isEven ||\n digits[i].isOdd && digits[j].isOdd)\n && digits[i] < digits[j]\n ){\n int temp = digits[i];\n digits[i] = digits[j];\n digits[j] = temp;\n }\n }\n largest = max(largest,int.parse(digits.join()));\n }\n return largest;\n }\n}\n```
1
0
['C', 'Python', 'C++', 'Java', 'JavaScript', 'C#', 'Dart']
0
largest-number-after-digit-swaps-by-parity
Greedy Algo
greedy-algo-by-pasumarthi_ashik-23hf
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
PASUMARTHI_ASHIK
NORMAL
2024-10-27T14:15:35.134637+00:00
2024-10-27T14:15:35.134667+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```javascript []\n/**\n * @param {number} num\n * @return {number}\n */\n\n\nvar largestInteger = function (num) {\n let odd = [];\n let even = [];\n\n const digits = String(num).split(\'\').map(Number);\n\n for (let i = 0; i < digits.length; i++) {\n if (digits[i] % 2 == 0) {\n even.push(digits[i]);\n }\n else {\n odd.push(digits[i]);\n }\n }\n\n even.sort((a, b) => b - a);\n odd.sort((a, b) => b - a);\n\n let result = [];\n let evenIndex = 0, oddIndex = 0;\n for (let digit of digits) {\n if (digit % 2 === 0) {\n\n result.push(even[evenIndex]);\n evenIndex++;\n } else {\n\n result.push(odd[oddIndex]);\n oddIndex++;\n }\n }\n\n return parseInt(result.join(\'\'), 10);\n};\n\n\n```
1
0
['JavaScript']
0
largest-number-after-digit-swaps-by-parity
0ms, beats 100% solution using 4 lists
0ms-beats-100-solution-using-4-lists-by-lhdqd
Intuition\n Describe your first thoughts on how to solve this problem. \nEven digits share their space and odd digits share a different space. Within each of th
chichi666
NORMAL
2024-10-24T20:56:33.600251+00:00
2024-10-24T21:01:00.280726+00:00
128
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEven digits share their space and odd digits share a different space. Within each of the 2 spaces, order the digits desc. Then reassemble all digits to get the result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIterate through all gigits for only once:\n-Use a list to store the even digits\n-Use a list to store even digits\' indices\n-Use a list to stroe the odd digits\n-Use a list to store odd digits\' indices\nOrder even digits desc\nOrder odd digits desc\nFor loop to reassemble:\n-If location is in even indices:\n--Assign the first number in even digits list to result, and pop it from the even list\n-If location is in odd indices:\n--Assign the first number in odd digits list to result, and pop it from the odd list\nReturn result\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nShould be O(1)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def largestInteger(self, num: int) -> int:\n result = []\n even_digits = []\n odd_digits = []\n even_indices = []\n odd_indices = []\n string_num = str(num)\n for i, digit in enumerate(string_num):\n if int(digit)%2 == 0:\n even_digits += [digit]\n even_indices += [i]\n else:\n odd_digits += [digit]\n odd_indices += [i]\n even_digits = sorted(even_digits, reverse = True)\n odd_digits = sorted(odd_digits, reverse = True)\n for i in range(len(string_num)):\n if i in even_indices:\n result += even_digits[0]\n even_digits.pop(0)\n if i in odd_indices:\n result += odd_digits[0]\n odd_digits.pop(0)\n return int("".join(result)) \n \n```
1
0
['Python3']
0
largest-number-after-digit-swaps-by-parity
Python 96.23%beat answer
python-9623beat-answer-by-army_y_wavy-a9r6
\n# Solution Explanation: Sorting Even and Odd Digits Separately\nIn this solution, the goal is to rearrange the digits of a given integer num such that the fin
Army_Y_Wavy
NORMAL
2024-08-23T02:19:32.310272+00:00
2024-08-23T02:23:17.086721+00:00
171
false
![image](https://assets.leetcode.com/users/images/df53c882-b0c8-4530-ace3-16c7ae000c54_1724379779.6406035.png)\n# **Solution Explanation: Sorting Even and Odd Digits Separately**\nIn this solution, the goal is to rearrange the digits of a given integer num such that the final integer is the largest possible, while maintaining the relative positions of even and odd digits.\n\n**Approach:**\n1. Digit Extraction: First, the digits of num are extracted and categorized into even and odd lists.\n\n1. Sorting: Both the even and odd digits are sorted in descending order. This allows us to use the largest possible digit from each category when reconstructing the number.\n\n1. Reconstruction: The original digit positions (even or odd) are preserved by replacing them with the largest available digit from the sorted lists.\n\n1. Final Conversion: The digits are then combined and converted back into an integer to produce the final result.\n\nThis method ensures that the largest possible number is formed while respecting the even-odd positioning constraints.\n\n\n```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n\t\t# Convert the number into a list of digits\n\t\tdigits = [int(digit) for digit in str(num)]\n\n\t\t# Separate even and odd digits into two lists\n\t\teven = []\n\t\todd = []\n\t\tfor digit in digits:\n\t\t\tif digit % 2 == 0:\n\t\t\t\teven.append(digit)\n\t\t\telse:\n\t\t\t\todd.append(digit)\n\n\t\t# Sort both lists in descending order\n\t\teven.sort(reverse=True)\n\t\todd.sort(reverse=True)\n\n\t\t# Reconstruct the number using the sorted even and odd digits\n\t\tans = []\n\t\tfor digit in digits:\n\t\t\tif digit % 2 == 0:\n\t\t\t\tans.append(even.pop(0))\n\t\t\telse:\n\t\t\t\tans.append(odd.pop(0))\n\n\t\t# Convert the list back to an integer and return it\n\t\tans = int(\'\'.join(map(str, ans)))\n\t\t\n\t\treturn ans\n\n```\n\nThis approach has a time complexity ofO(n log n), primarily due to the sorting steps, where n is the number of digits in the input number.\n\nFeel free to share your thoughts or any optimizations in the comments!
1
0
['Python', 'Python3']
0
largest-number-after-digit-swaps-by-parity
easy solution
easy-solution-by-arunkumarkandasamy-3jyz
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
arunkumarkandasamy
NORMAL
2024-07-21T17:39:20.208523+00:00
2024-07-21T17:39:20.208547+00:00
805
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```\n// import java.util.ArrayList;\n// import java.util.Collections;\n\nclass Solution {\n public int largestInteger(int num) {\n String s = String.valueOf(num);\n int n = s.length();\n \n ArrayList<Integer> evens = new ArrayList<>();\n ArrayList<Integer> odds = new ArrayList<>();\n \n // Separate the digits into even and odd lists\n for (int i = 0; i < n; i++) {\n int digit = s.charAt(i) - \'0\';\n if (digit % 2 == 0) {\n evens.add(digit);\n } else {\n odds.add(digit);\n }\n }\n \n // Sort both lists in descending order\n Collections.sort(evens, Collections.reverseOrder());\n Collections.sort(odds, Collections.reverseOrder());\n \n // Reconstruct the largest possible integer\n StringBuilder result = new StringBuilder();\n int evenIndex = 0, oddIndex = 0;\n for (int i = 0; i < n; i++) {\n int digit = s.charAt(i) - \'0\';\n if (digit % 2 == 0) {\n result.append(evens.get(evenIndex++));\n } else {\n result.append(odds.get(oddIndex++));\n }\n }\n \n // Convert the result to an integer and return\n return Integer.parseInt(result.toString());\n }\n}\n\n```
1
0
['Java']
0
largest-number-after-digit-swaps-by-parity
Using custom bubble sort for beautiful
using-custom-bubble-sort-for-beautiful-b-fo1m
Complexity\n- Time complexity: O(n^2) \n\n\n- Space complexity: O(1) \n\n# Code\npython\nclass Solution:\n def largestInteger(self, num: int) -> int:\n
tommy_dreck
NORMAL
2024-06-17T10:22:14.633107+00:00
2024-06-17T10:22:14.633127+00:00
368
false
# Complexity\n- Time complexity: $$O(n^2)$$ \n\n\n- Space complexity: $$O(1)$$ \n\n# Code\n```python\nclass Solution:\n def largestInteger(self, num: int) -> int:\n digits = []\n while num:\n digits.append(num % 10)\n num //= 10\n for i in range(len(digits) - 1, 0, -1):\n flag_odd_1 = digits[i] & 1\n for j in range(i - 1, -1, -1):\n if digits[i] < digits[j]:\n flag_odd_2 = digits[j] & 1\n if flag_odd_1 == flag_odd_2:\n digits[i], digits[j] = digits[j], digits[i]\n num = 0\n for i in range(len(digits) - 1, -1, -1):\n num = num * 10 + digits[i]\n return num\n \n\n \n \n\n \n```
1
0
['Python3']
0
largest-number-after-digit-swaps-by-parity
The simplest approach using two heaps, beat 99% of python users
the-simplest-approach-using-two-heaps-be-zzwz
Intuition\n Describe your first thoughts on how to solve this problem. \nbuild max heap for odd digits and another one for even digits\nloop over original num\n
Ahmad-Amer
NORMAL
2024-06-16T07:29:17.057915+00:00
2024-06-16T07:29:17.057951+00:00
70
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nbuild max heap for odd digits and another one for even digits\nloop over original num\nif digit is odd: append the maximum odd digit to the result, and remove it from the heap\nif digit is even: append the maximum even digit to the result, remove it from the heap\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlog(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```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n num = [int(i) for i in str(num)]\n odd_nums = [-i for i in num if i % 2 == 1]\n even_nums = [-i for i in num if i % 2 == 0]\n heapq.heapify(odd_nums)\n heapq.heapify(even_nums)\n res = \'\'\n for i in num:\n if i % 2 == 0:\n res += str(-heapq.heappop(even_nums))\n else:\n res += str(-heapq.heappop(odd_nums))\n return int(res)\n \n```
1
0
['Heap (Priority Queue)', 'Python3']
0