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
minimum-sum-of-four-digit-number-after-splitting-digits
Simple and best solution with logic mentioned. Upvote if you understood:)
simple-and-best-solution-with-logic-ment-rb41
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
razer7
NORMAL
2023-07-09T18:39:46.369243+00:00
2023-07-09T18:39:46.369262+00:00
674
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 minimumSum(int num) {\n vector<int> ans(4);\n for(int i=3;i>=0;i--)\n {\n ans[i]=num%10;\n num/=10;\n }\n\n /* to make min sum, the 1st elements of both num1 and num2 should be either arr[0] or arr[1] after sorting the arr, or we can say the the min elements. */\n sort(ans.begin(),ans.end());\n\n int sum1=(ans[0]*10 + ans[2]);\n int sum2=(ans[1]*10 + ans[3]);\n\n return sum1+sum2;\n }\n};\n```
6
0
['C++']
1
minimum-sum-of-four-digit-number-after-splitting-digits
simple java solution | 0ms
simple-java-solution-0ms-by-antovincent-c7lc
\n\n# Code\n\nclass Solution {\n public int minimumSum(int num) {\n int [] a=new int[4];\n int i=0;\n while(num>0){\n a[i++]=num%10;\n
antovincent
NORMAL
2023-05-09T08:16:34.702191+00:00
2023-05-09T08:16:34.702232+00:00
1,310
false
\n\n# Code\n```\nclass Solution {\n public int minimumSum(int num) {\n int [] a=new int[4];\n int i=0;\n while(num>0){\n a[i++]=num%10;\n num/=10;\n } \n Arrays.sort(a);\n return(((a[0]*10)+(a[3]))+((a[1]*10)+a[2]));\n }\n}\n```
6
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
my minimumSum
my-minimumsum-by-rinatmambetov-ii7z
# Intuition \n\n\n\n\n\n\n\n\n\n\n\n# Code\n\n/**\n * @param {number} num\n * @return {number}\n */\nvar minimumSum = function (num) {\n let str = num.toStri
RinatMambetov
NORMAL
2023-04-21T07:02:54.934527+00:00
2023-04-21T07:02:54.934570+00:00
1,285
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/**\n * @param {number} num\n * @return {number}\n */\nvar minimumSum = function (num) {\n let str = num.toString().split("").sort();\n return parseInt(str[0] + str[2]) + parseInt(str[1] + str[3]);\n};\n```
6
0
['JavaScript']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Easy Python Solution - minSum
easy-python-solution-minsum-by-gourav_si-kr27
\n\n# Code\n\nclass Solution:\n def minimumSum(self, num: int) -> int:\n l=[]\n while num != 0:\n l.append(num % 10)\n nu
Gourav_Sinha
NORMAL
2023-03-26T22:12:01.393286+00:00
2023-03-26T22:12:01.393317+00:00
1,466
false
\n\n# Code\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n l=[]\n while num != 0:\n l.append(num % 10)\n num = num // 10\n \n l.sort()\n res = (l[1] * 10 + l[2]) + (l[0] * 10 + l[3])\n return res\n```
6
0
['Python3']
2
minimum-sum-of-four-digit-number-after-splitting-digits
C++ 1-liner Easy & Simple Solution Ever
c-1-liner-easy-simple-solution-ever-by-s-ei4y
Approach\n Describe your approach to solving the problem. \nFirst off all we will split num 2932 into 2,9,3,2 and we will store them in vector a.\nThen we sort
sailakshmi1
NORMAL
2023-01-20T18:03:28.801906+00:00
2023-01-20T18:03:28.801949+00:00
1,758
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst off all we will split num 2932 into 2,9,3,2 and we will store them in vector a.\nThen we sort a , --------------> 2 , 2 , 3 , 9 .\nnow, the min sum possible is 22 + 29 .\n23 means 2*10+3 -----------------> a[0]*10 + a[2];\n29 means 2*10+9 -----------------> a[1]*10 + a[3];\n\nso we will return a[0]*10 + a[1]*10 + a[2] + a[3] \n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int>a(4);\n for(int i=0;i<a.size();i++){\n a[i] = num%10;\n num = num/10; // splitting number into digits & pushing into vector a \n }\n sort(a.begin(),a.end());\n return (a[0]+a[1])*10 + a[2]+a[3]; \n }\n};\n```
6
0
['C++']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Solution for C++ - sort and calcuate directly
solution-for-c-sort-and-calcuate-directl-c27b
cpp\nclass Solution\n{\npublic:\n int minimumSum(int num)\n {\n string s = to_string(num);\n sort(s.begin(), s.end());\n int res = (s
yehgoter
NORMAL
2022-02-05T16:10:36.703786+00:00
2022-02-05T16:10:36.703813+00:00
1,088
false
```cpp\nclass Solution\n{\npublic:\n int minimumSum(int num)\n {\n string s = to_string(num);\n sort(s.begin(), s.end());\n int res = (s[0] - \'0\' + s[1] - \'0\') * 10 + s[2] + s[3] - \'0\' - \'0\';\n return res;\n }\n};\n```
6
1
['C']
3
minimum-sum-of-four-digit-number-after-splitting-digits
O(1) Solution True Optimal Solution Beats 100% code.
o1-solution-true-optimal-solution-beats-lwcbq
SummaryBeats 100% of codes O(1) solution!ApproachCalculating all possible combinations of num example: 2932--> 29,32 22,93 92,23 .......etc. finding minimum sum
artherbhion2004
NORMAL
2025-02-07T06:13:28.466012+00:00
2025-02-07T06:13:28.466012+00:00
778
false
# Summary <!-- Describe your first thoughts on how to solve this problem. --> Beats 100% of codes O(1) solution! # Approach <!-- Describe your approach to solving the problem. --> Calculating all possible combinations of num example: 2932--> 29,32 22,93 92,23 .......etc. finding minimum sum of all pairs; # Complexity - Time complexity: O(1) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # 1.Code Final Improved Readablity: ```java [] class Solution { public int minimumSum(int num) { //Seperate Each Digits: int d1 = num / 1000; int d2 = (num / 100) % 10; int d3 = (num / 10) % 10; int d4 = num % 10; // Generate Combinations: int a = d1 * 10 + d2; int b = d3 * 10 + d4; int c = d1 * 10 + d4; int d = d2 * 10 + d3; int e = d2 * 10 + d1; int f = d4 * 10 + d3; int g = d4 * 10 + d1; int h = d1 * 10 + d3; int i = d2 * 10 + d4; int j = d4 * 10 + d2; int k = d3 * 10 + d1; //return Minimum: return Math.min(a + b, Math.min(j + k, Math.min(b + e, Math.min(c + d, Math.min(d + g, Math.min(a + f, h + i)))))); } } ``` # 2.Code ProtoType: ```java [] class Solution { public int minimumSum(int num) { int a= (num/1000*10)+(num/100)%10; int b=(num%100); int c=(num/1000*10)+(num%10); int d=(num%1000)/10; int e = ((num/100)%10)*10+(num/1000); int f=(num%10)*10+(num%100)/10; int g=num%10*10+num/1000; int h=num/1000*10+(num%100)/10; int i=((num/100)%10)*10+num%10; int j=num%10*10+(num%1000)/100; int k=(num%100)/10*10+num/1000; return Math.min(a+b,Math.min(j+k,Math.min(b+e,Math.min(c+d,Math.min(d+g,Math.min(a+f,h+i)))))); } } ```
5
0
['Math', 'Greedy', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
3
minimum-sum-of-four-digit-number-after-splitting-digits
Java Detailed Solution - O(nlog(n))
java-detailed-solution-onlogn-by-tranled-scdo
Intuition\n> Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.\n> Return the minimum possible sum of new1 and new2.\n\nI
tranleduyan
NORMAL
2024-02-16T23:34:52.522998+00:00
2024-07-03T21:22:34.996730+00:00
300
false
# Intuition\n> Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.\n> Return the minimum possible sum of new1 and new2.\n\nIt is easy to see that when given a 4-digit number, a pair of two-digit numbers is always smaller than a pair consisting of a 3-digit and 1-digit number. On closer inspection, the position that can make a 2-digit number significantly smaller is the tens place. For instance, if we have digits 0 and 1, 01 is smaller than 10 (given that trailing zeros are allowed). Thus, to make the two 2-digit numbers as small as possible, we can place the two minimum values in the tens place of the 4-digit number and put the larger ones in the ones place.\n\n# Approach\n1. Split the given number `num` into four separate digits. We can use an array to store these digits.\n - To get the four digits, simply modulo by 10 to get the numbers starting from the ones, repetitively until `num` is 0.\n2. Sort the array.\n - This way, the first two elements of the array are the two minimum digits, and the last two are larger digits.\n3. Construct the new numbers `new1` and `new2` with the minimum digits in the tens place. \n4. Return the sum of `new1` and `new2`. Since these are the two minimum numbers, the sum will also be the minimum.\n# Complexity\n- Time complexity: $$O(nlog(n))$$ where $$n$$ is always 4, which is the amount of digits of the number.\n\n- Space complexity: $$O(n)$$ where $$n$$ is is always 4, which is the amount of digits of the number. Remember, we use an array to store the digits.\n\n# Code\n```\nclass Solution {\n public int minimumSum(int num) {\n int[] digits = new int[4];\n for(int i = 0; i < 4; i++) {\n digits[i] = num % 10;\n num /= 10;\n }\n Arrays.sort(digits);\n int new1 = digits[0] * 10 + digits[2];\n int new2 = digits[1] * 10 + digits[3];\n\n return new1 + new2;\n }\n}\n```
5
0
['Java']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Convert into the list and then store the value..
convert-into-the-list-and-then-store-the-q4nc
Code\n\nclass Solution:\n def minimumSum(self, num: int) -> int:\n nums=list(str(num))\n nums.sort()\n return int(nums[0]+nums[-1])+int(
Mohan_66
NORMAL
2023-02-02T10:03:58.148258+00:00
2023-02-02T10:03:58.148359+00:00
736
false
# Code\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n nums=list(str(num))\n nums.sort()\n return int(nums[0]+nums[-1])+int(nums[1]+nums[2])\n \n```
5
0
['Python3']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Python | Solution For an Integer of Indefinite Length
python-solution-for-an-integer-of-indefi-7i4a
\nclass Solution:\n def minimumSum(self, num: int) -> int:\n sorted_num = sorted(list(str(num)))\n \n num1 = num2 = ""\n for i in
lex81722
NORMAL
2023-01-05T02:19:03.479985+00:00
2023-01-05T02:19:03.480019+00:00
680
false
```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n sorted_num = sorted(list(str(num)))\n \n num1 = num2 = ""\n for i in range(len(sorted_num)):\n if i % 2 == 0:\n num1 += sorted_num[i]\n else:\n num2 += sorted_num[i]\n \n return int(num1) + int(num2)\n```
5
0
['Python']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Javascript Solution
javascript-solution-by-abdllhbayram-khgk
\nvar minimumSum = function(num) {\n let numbers = []\n for(let i = 0; i<4; i++){\n numbers.push(~~num % 10)\n num /= 10\n }\n const so
a_bayram
NORMAL
2022-05-20T22:27:44.522961+00:00
2022-05-20T22:27:44.522987+00:00
1,402
false
```\nvar minimumSum = function(num) {\n let numbers = []\n for(let i = 0; i<4; i++){\n numbers.push(~~num % 10)\n num /= 10\n }\n const sorted = numbers.sort((a,b) => b - a)\n return sorted[0] + sorted[1] + (10 *( sorted[2] + sorted[3]))\n};\n```
5
0
['JavaScript']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Very easy solution (python)
very-easy-solution-python-by-jonathan-ng-1ot7
The idea here is to create a list of digits in the num. then sort the digits \nafter sorting, we have a, b, c, d as 4 digits. the answer is ac + bd (or ad + bc)
jonathan-nguyen
NORMAL
2022-02-05T16:58:16.814037+00:00
2022-02-05T16:59:47.872169+00:00
950
false
The idea here is to create a list of digits in the num. then sort the digits \nafter sorting, we have a, b, c, d as 4 digits. the answer is ac + bd (or ad + bc).\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n list_digits = []\n while num > 0:\n list_digits.append(num % 10)\n num = num // 10\n \n a, b, c, d= sorted(list_digits)\n return 10 * a + c + 10*b + d\n```
5
0
['Python', 'Python3']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Very Easy O(1) Time complexity solution
very-easy-o1-time-complexity-solution-by-3adp
Intuition Extract and Sort the Digits: Break the 4-digit number into its digits and sort them in ascending order. Sorting ensures smaller digits can be placed
aman8558
NORMAL
2025-01-22T16:57:37.771853+00:00
2025-01-22T16:57:37.771853+00:00
474
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> 1. Extract and Sort the Digits: Break the 4-digit number into its digits and sort them in ascending order. Sorting ensures smaller digits can be placed in more significant positions to minimize the sum. 2. Form Two Numbers Alternately: Distribute the sorted digits alternately between two numbers. Start with the smallest digit in the tens place of one number, then the next smallest in the tens place of the other number, and so on. 3. Calculate the Minimum Sum: Combine the digits to form the two numbers and return their sum. This ensures the smallest possible sum for the given digits. # Approach <!-- Describe your approach to solving the problem. --> 1. Make a empty list 2. Extract the digits from the number and store them in your list. 3. Sort the list. 4. Then make two variables num1 and num2. 5. Make the combination of first digit with the last one as the last one is the maximum one so we can't put it in one's place so we put it with the smallest one. 6. Now complete your answer. # Complexity - Time complexity: O(1) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def minimumSum(self, num: int) -> int: l=[] while num!=0: l.append(num%10) num//=10 l.sort() num1=(l[0]*10)+l[3] num2=(l[1]*10)+l[2] return num1+num2 ```
4
0
['Math', 'Sorting', 'Python', 'Python3']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Simple java program for beginners
simple-java-program-for-beginners-by-pra-x2gh
Intuition\nWhen i looked into the problem it was easier to judge because the number they will be give is strictly a 4-digit number. Considering that they are as
Prasath_T
NORMAL
2024-03-09T15:34:47.794603+00:00
2024-03-10T04:29:09.862375+00:00
364
false
# Intuition\nWhen i looked into the problem it was easier to judge because the number they will be give is strictly a 4-digit number. Considering that they are asking the min sum.....lets say we have 2 and 4 , while combining it together 24 is smaller than 42 so we have sort and make sure the min digit is in the ten\'s position than in the ones\'s position.\n# Approach\nFirst the number is converted into an array by using the modulus concept which i assume you guys know and then add then sort the array.\n\nWhen you sort it the first two elements of the array are the two minimum digits, and the last two are larger digits.\n\nConstruct the new numbers n1 and n2 with the minimum digits in the tens place.\n\nAnd then return n1+n2\n# Complexity\n- Time complexity: O(1)\n- Space complexity: O(1)\n# Code\n```\nclass Solution {\n public int minimumSum(int num) {\n int[] arr = new int[4];\n for(int i=0;i<4;i++){\n arr[i] = num%10;\n num/=10;\n }\n Arrays.sort(arr);\n int n1 = (arr[0])*10 + arr[2];\n int n2 = (arr[1])*10 + arr[3];\n return n1+n2;\n }\n}\n```\n\nPLS UPVOTE......
4
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Easy to understand solution using c++ || Sorting || Array
easy-to-understand-solution-using-c-sort-t2wg
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nAt first we will split
ayush_pratap27
NORMAL
2024-02-21T12:17:50.942038+00:00
2024-02-21T12:17:50.942060+00:00
35
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAt first we will split num and we will store it\'s digit in vector v.\nThen we sort the vector v.\nNow the two numbers whose sum is minimum are (v[0]*10 + v[2]) and (v[1]*10 + v[3]);\n\nSo we will return the sum of these two numbers.\n\n# Complexity\n- Time complexity: O(nlogn) \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nComplexity of sort function is nlogn\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int> v;\n while(num){\n v.push_back(num%10);\n num=num/10;\n }\n sort(v.begin(),v.end());\n int new1=v[0]*10 + v[2];\n int new2=v[1]*10 + v[3];\n\n return new1+new2;\n \n }\n};\n```
4
0
['Array', 'Sorting', 'C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
c++ solution using frequency array
c-solution-using-frequency-array-by-luff-s4a2
Intuition\nMost significant digit will contribute the maximum amount to the sum ( 10\'s digit in this case )\n\n# Approach\nMake a frequnecy array storing the f
luffy0908
NORMAL
2023-03-19T06:14:12.556495+00:00
2023-03-19T06:14:12.556540+00:00
1,206
false
# Intuition\nMost significant digit will contribute the maximum amount to the sum ( 10\'s digit in this case )\n\n# Approach\nMake a frequnecy array storing the frequncy of each digit. As we know while summing 2 digit numbers, 10s digit would contribute the maximum to the sum so we aim to use the minimum possible digit as 10\'s digit. The first two digits in the sorted frequncy array would be the smallest so make them the 10\'s digit and the remaining two as the 1\'s digit.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\n#include <vector>\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector <int> v(10,0);\n int copy = num;\n while(copy){\n int rem = copy % 10;\n v[rem] += 1;\n copy /= 10;\n }\n int count = 2;\n int ans = 0;\n for( int i = 0; i < 10; i++ ){\n while( v[i] != 0 ){\n if(count > 0){\n ans += i * 10;\n count -= 1;\n }\n else{\n ans += i;\n }\n v[i] -= 1;\n }\n }\n return ans;\n }\n};\n```
4
0
['Hash Table', 'C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Python || Easy || 3Lines || Sorting ||
python-easy-3lines-sorting-by-pulkit_upp-7syf
\nclass Solution:\n def minimumSum(self, num: int) -> int:\n n=[num//1000,(num//100)%10,(num//10)%10,num%10] #This line will convert the four digit no
pulkit_uppal
NORMAL
2022-11-16T20:39:19.942722+00:00
2022-11-25T16:07:59.703250+00:00
1,490
false
```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n n=[num//1000,(num//100)%10,(num//10)%10,num%10] #This line will convert the four digit no. into array \n n.sort() #It will sort the digits in ascending order\n return (n[0]*10+n[3])+(n[1]*10+n[2]) # Combination of first and last and the remaining two digits will give us the minimum value\n```\n\n**Upvote if you like the solution or ask if there is any query**
4
0
['Sorting', 'Python', 'Python3']
2
minimum-sum-of-four-digit-number-after-splitting-digits
Java | 0 ms | 100% faster
java-0-ms-100-faster-by-aditi_sinha123-uls8
\nclass Solution {\n public int minimumSum(int num) {\n int arr[]=new int[4];\n int i=0;\n int num2=num;\n while(num>0){\n
Aditi_sinha123
NORMAL
2022-10-24T13:09:57.828380+00:00
2022-10-24T13:09:57.828416+00:00
684
false
```\nclass Solution {\n public int minimumSum(int num) {\n int arr[]=new int[4];\n int i=0;\n int num2=num;\n while(num>0){\n arr[i]=num%10;\n num=num/10;\n i++;\n }\n Arrays.sort(arr);\n int n1=arr[3]+10*arr[0];\n int n2=arr[2]+ 10*arr[1];\n return n1+n2;\n }\n}\n```
4
0
['Java']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Go funny solution
go-funny-solution-by-tuanbieber-i68h
\nfunc minimumSum(num int) int {\n var digits []int\n \n for num > 0 {\n digits = append(digits, num%10)\n num /= 10\n }\n \n so
tuanbieber
NORMAL
2022-08-22T05:25:35.033821+00:00
2022-08-22T05:25:35.033868+00:00
412
false
```\nfunc minimumSum(num int) int {\n var digits []int\n \n for num > 0 {\n digits = append(digits, num%10)\n num /= 10\n }\n \n sort.Ints(digits)\n \n return digits[0]*10 + digits[2] + digits[1]*10 + digits[3]\n}\n```
4
0
['Go']
2
minimum-sum-of-four-digit-number-after-splitting-digits
Javascript
javascript-by-muskan_bandil-pvft
\nvar minimumSum = function(num) {\n num = num.toString().split("").sort();\n return (Number(num[0]+num[2]) + Number(num[1]+num[3]) )\n};\n
muskan_bandil
NORMAL
2022-04-17T09:33:36.745373+00:00
2022-04-17T09:33:36.745412+00:00
230
false
```\nvar minimumSum = function(num) {\n num = num.toString().split("").sort();\n return (Number(num[0]+num[2]) + Number(num[1]+num[3]) )\n};\n```
4
0
[]
0
minimum-sum-of-four-digit-number-after-splitting-digits
Accepted: C++ 0ms
accepted-c-0ms-by-mayankatleetcode-8gvf
Approach:\nAs it is already mentioned that we have only 4 digits so we can use 4 size vector to store the digits.\n- Store the digits in vector.\n- Sort the vec
MayankAtLeetcode
NORMAL
2022-03-23T19:22:24.218909+00:00
2022-03-23T19:22:24.218943+00:00
128
false
**Approach:**\nAs it is already mentioned that we have only 4 digits so we can use 4 size vector to store the digits.\n- Store the digits in vector.\n- Sort the vector.\n- To keep the number small, start with the number with lowest digits. So lets create first numbers first digit with 0th element of the sorted vector and create first digit of the second number with the 1st index digit of the vector.\n- sum of the created numbers is the answer.\n```\nint minimumSum(int num) {\n vector<int> digit(4, 0);\n for(int x=0; x < 4; x++) {\n digit[x] = num%10;\n num = num/10;\n }\n sort(digit.begin(), digit.end());\n int f = digit[0] * 10 + digit[2];\n int s = digit[1] * 10 + digit[3];\n \n return f + s;\n }\n```
4
0
['C']
1
minimum-sum-of-four-digit-number-after-splitting-digits
[Python3] Greedy Algorithm - Priority Queue (min heap) - Easy understanding
python3-greedy-algorithm-priority-queue-4i62o
TC: O(4log3)\nSC: O(4)\n\n\ndef minimumSum(self, num: int) -> int:\n digits = []\n while num:\n heappush(digits, num % 10)\n
dolong2110
NORMAL
2022-02-22T20:37:40.891156+00:00
2022-02-22T20:39:02.589522+00:00
193
false
TC: O(4log3)\nSC: O(4)\n\n```\ndef minimumSum(self, num: int) -> int:\n digits = []\n while num:\n heappush(digits, num % 10)\n num //= 10\n \n i = 0\n num1, num2 = 0, 0\n while digits:\n if i % 2 == 0:\n num1 = num1 * 10 + heappop(digits)\n i += 1\n else:\n num2 = num2 * 10 + heappop(digits)\n i -= 1\n \n return num1 + num2\n```
4
1
['Greedy', 'Heap (Priority Queue)', 'Python', 'Python3']
0
minimum-sum-of-four-digit-number-after-splitting-digits
C++ Easy Solution
c-easy-solution-by-mr__mk__12-iq5r
We can directly sort 4 digits and select the first and third digit form num1 number .Then select 2 and last digit and num2 and then return the sum of num1 and n
mr__mk__12
NORMAL
2022-02-05T16:04:31.986732+00:00
2022-02-05T16:04:31.986770+00:00
129
false
We can directly sort 4 digits and select the first and third digit form num1 number .Then select 2 and last digit and num2 and then return the sum of num1 and num2.\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int>digit(4);\n\t\twhile(num > 0)\n\t\t{\n\t\t\tdigit.push_back(num%10)\n\t\t\tnum/=10;\n\t\t}\n\t\t\n\t\twhile(digit.size()<4)\n\t\t\tdigit.push_back(0);\n\t\t\t\n\t\tsort(digit.begin(),digit.end());\n\t\tint num1 = 0 , num2 = 0;\n\t\t\n\t\tnum1 = digit[0]*10 + digit[2]; //from first number\n\t\tnum2 = digit[1]*10 + digit[3]; //form second number\n\t\t\n\t\treturn num1+num2;\n }\n};\n```
4
1
['Sorting']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Easy Approach
easy-approach-by-abanoub7asaad-j72z
cpp\nclass Solution {\npublic:\n int minimumSum(int num) {\n \n int a, b, c, d;\n vector<int> arr;\n \n a = num%10, num/=1
abanoub7asaad
NORMAL
2022-02-05T16:02:00.150063+00:00
2022-02-05T16:02:00.150107+00:00
801
false
```cpp\nclass Solution {\npublic:\n int minimumSum(int num) {\n \n int a, b, c, d;\n vector<int> arr;\n \n a = num%10, num/=10;\n b = num%10, num/=10;\n c = num%10, num/=10;\n d = num%10, num/=10;\n \n arr = {a, b, c, d};\n sort(arr.begin(), arr.end());\n \n return (10*arr[0]+arr[2])+(10*arr[1]+arr[3]);\n }\n};\n```
4
0
['C']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Simple || Easy to Understand || 100% Beats
simple-easy-to-understand-100-beats-by-k-1o8f
IntuitionApproachComplexity Time complexity: Space complexity: Code
kdhakal
NORMAL
2025-02-26T17:38:54.874186+00:00
2025-02-26T17:38:54.874186+00:00
178
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 [] class Solution { public int minimumSum(int num) { int[] digits = new int[4]; int i = 0; while(num > 0) { digits[i++] = num % 10; num /= 10; } Arrays.sort(digits); return digits[0] * 10 + digits[2] + digits[1] * 10 + digits[3]; } } ```
3
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
easiest way PYTHON
easiest-way-python-by-justingeorge-83ty
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
justingeorge
NORMAL
2024-03-17T04:04:42.557285+00:00
2024-03-17T04:04:42.557328+00:00
404
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 minimumSum(self, num: int) -> int:\n\n num=str(num)\n num=list(num)\n num.sort()\n a=num[0]+num[2]\n b=num[1]+num[3]\n \n return int(a) + int(b)\n\n```
3
0
['Python3']
0
minimum-sum-of-four-digit-number-after-splitting-digits
C solution
c-solution-by-lathcsmath-r30j
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
lathcsmath
NORMAL
2023-12-14T16:28:38.879107+00:00
2023-12-14T16:28:38.879136+00:00
134
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(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nint minimumSum(int num) \n{\n int digits[4];\n for(int i = 0; i < 4; i++)\n {\n digits[i] = num % 10;\n num /= 10;\n }\n for(int i = 0; i < 3; i++)\n {\n for(int j = 3; j > i; j--)\n {\n if(digits[j] < digits[j - 1])\n {\n int tmp = digits[j];\n digits[j] = digits[j - 1];\n digits[j - 1] = tmp;\n }\n }\n }\n return (digits[0] + digits[1]) * 10 + digits[2] + digits[3]; \n}\n```
3
0
['C']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Sort Solution (with step by step explanation)
sort-solution-with-step-by-step-explanat-ed7e
Intuition\nwe will use sort to solve this problem\n# Approach\nwe convert number to string and split to digits, then we sort it and after that we return sum of
alekseyvy
NORMAL
2023-11-15T20:07:19.207488+00:00
2023-11-15T20:07:19.207515+00:00
141
false
# Intuition\nwe will use sort to solve this problem\n# Approach\nwe convert number to string and split to digits, then we sort it and after that we return sum of digits\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n# Code\n```\nfunction minimumSum(num: number): number {\n // convert number to string, split to digit and sort\n const sorted = String(num).split("").sort((a, b) => +a - +b);\n // return sum of numbers at inidicies 0 and 2 with numbers at indicies 2 and 3\n return Number(`${sorted[0]}${sorted[2]}`) + Number(`${sorted[1]}${sorted[3]}`)\n};\n```
3
0
['TypeScript']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Simple method with time 2ms and space required 6.44MB.
simple-method-with-time-2ms-and-space-re-v398
Intuition\n Describe your first thoughts on how to solve this problem. \nHow about storing each element/digit of the number in a vector of int type and then sor
Joshi_Y
NORMAL
2023-11-15T11:14:13.060573+00:00
2023-11-15T11:14:13.060595+00:00
313
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHow about storing each element/digit of the number in a vector of `int` type and then sorting it in ascending order, then adding the two terms formed from the first and fourth(last) element along with the second and the third element.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe detailed explanation of the program is as:\n1. A vector of integers named `res` is initialized.\n2. A while loop is executed as long as the variable `num` is non-zero.\n3. Inside the loop, the value of `num` is appended to the `res` vector using the `push_back()` function.\n4. The value of `num` is divided by 10 in each iteration to extract the digits.\n5. After the loop, the `res` vector is sorted in ascending order using the `sort()` function.\n6. Two new variables, `num1` and `num2`, are calculated by combining specific elements from the sorted "res" vector.\n7. Finally, the sum of `num1` and `num2` is returned.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n logn) \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int> res;\n while(num)\n {\n res.push_back(num%10);\n num/=10;\n }\n sort(res.begin(),res.end());\n int num1=(res[0]*10)+res[3];\n int num2=(res[1]*10)+res[2];\n return num1+num2;\n }\n};\n```
3
0
['Array', 'Greedy', 'Sorting', 'C++']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Python || 2 Approach (Math, String) || 99.70%beats
python-2-approach-math-string-9970beats-hikog
\n# Code\n> # Full Math Approach\n\nclass Solution:\n def minimumSum(self, num: int) -> int:\n n = []\n while num > 0:\n n.append(nu
vvivekyadav
NORMAL
2023-10-04T16:02:04.798830+00:00
2023-10-04T16:02:04.798869+00:00
465
false
\n# Code\n> # Full Math Approach\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n n = []\n while num > 0:\n n.append(num%10)\n num = num // 10\n \n n.sort()\n\n n1 = n[0] * 10 + n[-1]\n n2 = n[1] * 10 + n[-2]\n return n1+ n2\n\n\n\n```\n\n> # String Approach\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n num = \'\'.join(sorted(str(num)))\n return int(num[0]+num[3]) + int(num[1]+num[2])\n\n\n#\n```
3
0
['Math', 'String', 'Greedy', 'Sorting', 'Python', 'Python3']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Easy code
easy-code-by-swapnili019-x26c
Intuition\nEasy to Understand\n# Approach\n1)int -> string\n2)sort string\n3)fix at correct string\n4)string to int and return its sum\n\n# Complexity\n- Time c
free_farm_019
NORMAL
2023-07-02T21:12:39.195317+00:00
2023-07-02T21:12:39.195342+00:00
19
false
# Intuition\nEasy to Understand\n# Approach\n1)int -> string\n2)sort string\n3)fix at correct string\n4)string to int and return its sum\n\n# Complexity\n- Time complexity:\nO(n) n <= 4 so o(1);\n- Space complexity:\n- o(1)\n\n\n# Code\n```\nclass Solution {\nint myAtoi(string str)\n{\n int res = 0;\n \n res = res * 10 + str[i] - \'0\';\n \n return res;\n}\npublic:\n int minimumSum(int num) {\n string s = to_string(num);\n sort(s.begin(), s.end());\n string a = "", b = "";\n a.push_back(s[0]);\n a.push_back(s[2]);\n b.push_back(s[1]);\n b.push_back(s[3]);\n\n int x = myAtoi(a);\n int y = myAtoi(b);\n\n return x+y;\n\n }\n};\n```
3
0
['Math', 'C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Best approach ||CPP|| solution 0ms runtime
best-approach-cpp-solution-0ms-runtime-b-sl86
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThe given code defines a class named Solution with a member function mini
madhavbsnl013
NORMAL
2023-07-01T09:17:00.901744+00:00
2023-07-01T09:24:34.097821+00:00
629
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe given code defines a class named `Solution` with a member function `minimumSum`. This function takes an integer `num` as input and calculates the minimum sum of two numbers by rearranging the digits of `num`.\n\nHere\'s a step-by-step explanation of the code:\n\n1. Create an empty vector `v` to store the individual digits of the input number `num`.\n\n2. Enter a while loop that continues until `num` becomes zero. Inside the loop:\n - Get the last digit of `num` by taking the modulus (`num % 10`), which gives the remainder when `num` is divided by 10.\n - Append the last digit to the vector `v`.\n - Update `num` by dividing it by 10 (`num = num / 10`) to remove the last digit.\n\n3. Sort the vector `v` in ascending order using `sort(v.begin(), v.end())`. This will rearrange the digits in `v` from smallest to largest.\n\n4. Create two numbers, `num1` and `num2`, by combining specific digits from the sorted vector `v`:\n - `num1` is formed by taking the smallest digit (`v[0]`) and the third smallest digit (`v[2]`).\n - `num2` is formed by taking the second smallest digit (`v[1]`) and the fourth smallest digit (`v[3]`).\n\n5. Return the sum of `num1` and `num2` as the minimum sum of two numbers.\n\nIt\'s important to note that this code assumes the input `num` has at least four digits. If `num` has fewer than four digits, the code may produce unexpected results or encounter runtime errors.\n\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector <int> v;\n while(num){\n v.push_back(num%10);\n num=num/10;\n }\n sort(v.begin(),v.end());\n int num1=v[0]*10+v[2],num2=v[1]*10+v[3];\n return num1+num2; \n\n }\n};\n```
3
0
['Math', 'Greedy', 'Sorting', 'C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
C++ Solution || Beats 100% || Runtime 0ms
c-solution-beats-100-runtime-0ms-by-asad-r0j5
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
Asad_Sarwar
NORMAL
2023-03-12T21:49:32.258706+00:00
2023-03-12T21:49:32.258733+00:00
624
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 minimumSum(int num) {\n\n vector<int> v;\n while(num!=0)\n {\n v.push_back(num%10);\n num=num/10;\n }\n sort(v.begin(),v.end());\n int ans=v[0]*10+v[3] + v[1]*10+v[2];\n return ans;\n\n\n }\n};\n```
3
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
C# easy solution.
c-easy-solution-by-aloneguy-hh6y
\n# Complexity\n- Time complexity: 26 ms.Beats 62.7% of other solutions.\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: 26.5 Mb.Beats 92.7%
aloneguy
NORMAL
2023-03-10T14:13:42.382425+00:00
2023-03-10T14:13:42.382472+00:00
106
false
\n# Complexity\n- Time complexity: 26 ms.Beats 62.7% of other solutions.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 26.5 Mb.Beats 92.7% of other solutions.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int MinimumSum(int num) {\n int[] arr=new int[4];\n int i=0;\n while(i<4){\n arr[i]=num%10;\n num/=10;\n i++;\n } \n Array.Sort(arr);\n return (arr[0]+arr[1])*10+arr[3]+arr[2];\n }\n}\n```
3
0
['Array', 'Math', 'C#']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Simple Solution || Minimum sum of four digit number after splitting digits
simple-solution-minimum-sum-of-four-digi-ijuh
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
himshrivas
NORMAL
2023-02-13T14:08:12.770278+00:00
2023-02-13T14:08:12.770320+00:00
910
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 minimumSum(self, num: int) -> int:\n l=[]\n while(num!=0):\n l.append(num%10)\n num//=10\n l.sort()\n result=(l[1]*10+l[2])+(l[0]*10+l[3])\n return result\n \n```
3
0
['Python3']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Easy java solution
easy-java-solution-by-theycallmeprem-2p83
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
TheyCallMePrem
NORMAL
2023-01-06T17:33:24.285179+00:00
2023-01-06T17:33:24.285228+00:00
1,138
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 public int minimumSum(int num) {\n \n int nos[] = new int[4];\n\n for(int i=0;i<4;i++){\n nos[i]=num%10;\n num/=10;\n }\n\n Arrays.sort(nos);\n // System.out.print(nos[1]);\n // int sol1=nos[0]*10 + nos[3] + nos[1]*10 + nos[2];\n // int sol2=nos[1]*10 + nos[3] + nos[0]*10 + nos[2];\n // return Math.min(sol1, sol2);\n\n return Math.min(nos[0]*10 + nos[3] + nos[1]*10 + nos[2],nos[1]*10 + nos[3] + nos[0]*10 + nos[2] );\n }\n}\n```
3
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
C++ | 3 lines | 3 methods | 0 bishes
c-3-lines-3-methods-0-bishes-by-lraml-3l8v
The two minimum digits should be the tenths places of our two digit numbers\n Eg : 3425 -> minDigit1 = 2\n minDigit2 = 3\n res = 25+34 OR
lRaml
NORMAL
2022-12-26T18:52:39.653495+00:00
2022-12-26T18:52:39.653538+00:00
366
false
### The two minimum digits should be the tenths places of our two digit numbers\n Eg : 3425 -> minDigit1 = 2\n minDigit2 = 3\n res = 25+34 OR 24+35\n### Method1 : string\n```c++\nint minimumSum(int n) {\n string s = to_string(n);\n sort(s.begin(), s.end());\n return (s[0]-\'0\' + s[1]-\'0\') * 10 + s[2]-\'0\' + s[3]-\'0\';\n```\n### Method2 : array\n```c++\nint minimumSum(int n) {\n int arr[4] = {n%10,n/10%10,n/100%10,n/1000%10};\n sort(begin(arr),end(arr));\n return arr[0]*10 + arr[1]*10 + arr[2] + arr[3];\n```\n### Method3: Brainless (\u02F5 \u0361\xB0 \u035C\u0296 \u0361\xB0\u02F5)\n```c++\nint minimumSum(int n) {\n short n1 = n%10;\n short n2 = n/10%10;\n short n3 = n/100%10;\n short n4 = n/1000%10;\n\n short ans1 = n1*10+n2*10+n3+n4;\n short ans2 = n1*10+n3*10+n2+n4;\n short ans3 = n1*10+n4*10+n2+n3;\n short ans4 = n2*10+n3*10+n1+n4;\n short ans5 = n2*10+n4*10+n1+n3;\n short ans6 = n3*10+n4*10+n1+n2;\n\n return min(ans1,min(ans2,min(ans3,min(ans4,min(ans5,ans6)))));\n\n```
3
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Simple C++ Solution || Easy to Understand.
simple-c-solution-easy-to-understand-by-ogg9o
----------------------------------------------------------------------\nSolution: 1\n\n----------------------------------------------------------------------\n\
codingstar2001
NORMAL
2022-10-22T10:16:23.981993+00:00
2022-10-22T10:16:23.982028+00:00
797
false
----------------------------------------------------------------------\n**Solution: 1**\n\n----------------------------------------------------------------------\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n string str = to_string(num);\n sort(str.begin(),str.end());\n\n int ans = (str[0]-\'0\' + str[1]-\'0\')*10 + str[2]-\'0\' + str[3]-\'0\';\n return ans;\n }\n};\n```\n----------------------------------------------------------------------\n\n**Solution: 2**\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int> v;\n\n while(num!=0)\n {\n int rem = num%10;\n v.push_back(rem);\n num /= 10;\n }\n\n sort(v.begin(),v.end());\n\n int num1 = v[0]*10+v[3];\n int num2 = v[1]*10+v[2];\n\n int ans = num1+num2;\n return ans;\n }\n};\n```\n\n----------------------------------------------------------------------\n**Analysis:**\n\n----------------------------------------------------------------------\n\n**Time Complexity:** ```O(NlogN)``` ----> As we used the sort function to sort the array.\n**Space Complexity**: ```O(n)``` ----> As we created the external Vector.\n\n----------------------------------------------------------------------\nIf this solution, helps you then please ```Upvote.```\ntill then **Keep Learning, Keep Exploring!!!**\n\n\n$$Thank You!$$\n\n----------------------------------------------------------------------\n\n\n
3
0
['C++']
2
minimum-sum-of-four-digit-number-after-splitting-digits
✔️ Easy Solution Using C++ || Best Solution || 100% Accepted
easy-solution-using-c-best-solution-100-is1ho
\nclass Solution {\npublic:\n int minimumSum(int num) {\n int arr[4]; // declaring an array\n arr[0] = num%10; //storing each digit in this arr
Viraat_28
NORMAL
2022-08-27T18:44:27.508259+00:00
2022-08-27T18:44:27.508300+00:00
940
false
```\nclass Solution {\npublic:\n int minimumSum(int num) {\n int arr[4]; // declaring an array\n arr[0] = num%10; //storing each digit in this array\n arr[1] = (num/10)%10;\n arr[2] = (num/100)%10;\n arr[3] = (num/1000)%10;\n sort(arr, arr + 4);\n return (arr[0]*10+arr[2]) + (arr[1]*10+arr[3]); //for ex{2,2,3,9} --> {23+29}\n }\n};\n```
3
0
['C', 'C++']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Java Easiest Solution || Faster than 90% of online submission || 1Ms Runtime
java-easiest-solution-faster-than-90-of-3rno4
\nclass Solution {\n public int minimumSum(int num) {\n int[] digits = new int[4];\n int k =0;\n while(num>0)\n {\n di
Hemang_Jiwnani
NORMAL
2022-08-11T12:19:59.081541+00:00
2022-08-11T12:19:59.081587+00:00
496
false
```\nclass Solution {\n public int minimumSum(int num) {\n int[] digits = new int[4];\n int k =0;\n while(num>0)\n {\n digits[k++] = num%10;\n num/=10;\n }\n Arrays.sort(digits);\n return (digits[0]*10+digits[3])+(digits[1]*10+digits[2]);\n }\n}\n```
3
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
only one loop || faster 83% || memory 78%
only-one-loop-faster-83-memory-78-by-shi-37we
\nclass Solution {\n public int minimumSum(int num) {\n int[] n = new int[4];\n int index=0;\n while(num>0)\n {\n n[in
Shivalika_1611
NORMAL
2022-03-11T05:09:12.477338+00:00
2022-03-11T05:09:12.477365+00:00
341
false
```\nclass Solution {\n public int minimumSum(int num) {\n int[] n = new int[4];\n int index=0;\n while(num>0)\n {\n n[index++] = num%10;\n num/=10;\n }\n Arrays.sort(n);\n return (n[0]*10 + n[2] + n[1]*10 + n[3]);\n \n }\n}\n```
3
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Beginner friendly python solution
beginner-friendly-python-solution-by-him-mde2
Time Complexity : O(n*logn)\n\nclass Solution(object):\n def minimumSum(self, num):\n arr = sorted(str(num))\n return int(arr[0] + arr[3]) + in
HimanshuBhoir
NORMAL
2022-03-06T03:17:12.904080+00:00
2022-03-07T01:14:49.678773+00:00
274
false
**Time Complexity : O(n*logn)**\n```\nclass Solution(object):\n def minimumSum(self, num):\n arr = sorted(str(num))\n return int(arr[0] + arr[3]) + int(arr[1] + arr[2])\n```
3
0
['Python']
2
minimum-sum-of-four-digit-number-after-splitting-digits
C++ solution||0 ms
c-solution0-ms-by-rag1212-agw7
class Solution {\npublic:\n int minimumSum(int num) {\n string str = to_string(num);\n sort(str.begin(), str.end());\n int n = ((str[0]-
rag1212
NORMAL
2022-02-08T14:21:59.258573+00:00
2022-02-08T14:21:59.258617+00:00
255
false
class Solution {\npublic:\n int minimumSum(int num) {\n string str = to_string(num);\n sort(str.begin(), str.end());\n int n = ((str[0]-\'0\')*10 + str[2]-\'0\')+((str[1]-\'0\')*10 + str[3]-\'0\');\n return n;\n }\n};
3
0
['String', 'C', 'Sorting']
1
minimum-sum-of-four-digit-number-after-splitting-digits
simplest sol ever
simplest-sol-ever-by-sandeep_py-3okg
int minimumSum(int num) {\n\n int arr[4];\n int i=0;\n while(num!=0){\n arr[i]=num%10;\n num=num/10;\n i++
Sandeep_py
NORMAL
2022-02-05T19:17:23.971119+00:00
2022-02-05T19:17:42.433903+00:00
28
false
int minimumSum(int num) {\n\n int arr[4];\n int i=0;\n while(num!=0){\n arr[i]=num%10;\n num=num/10;\n i++;\n }\n sort(arr,arr+4);\n int r=arr[0]*10+arr[2];\n int s=arr[1]*10+arr[3];\n return r+s;\n }
3
0
[]
0
minimum-sum-of-four-digit-number-after-splitting-digits
Bitmask Solution || OVERKILL
bitmask-solution-overkill-by-jyoti369-g6cc
1.Use all mask from 1 to 14 ("1111" means 15 so, we have to take 14 as upper bound so that non-empty 2nd list is formed)\n2.Make two list for each mask(1st list
jyoti369
NORMAL
2022-02-05T17:38:58.288004+00:00
2022-02-05T18:24:39.290027+00:00
178
false
1.Use all mask from 1 to 14 ("1111" means 15 so, we have to take 14 as upper bound so that non-empty 2nd list is formed)\n2.Make two list for each mask(1st list - set bits, 2nd list-unset bits)\n3.Sort those list\n4.Form two number from those lists\n5.Calculate sum\n6.Track minimum\n\nJAVA OVERKILL SOLN.\n\n```\nclass Solution {\n public int minimumSum(int num) {\n int sum=Integer.MAX_VALUE;\n StringBuilder sb=new StringBuilder();\n sb.append(num);\n String y=sb.toString();\n char ar[]=y.toCharArray();\n for(int i=1;i<15;i++)\n {\n ArrayList<Character> al1=new ArrayList<>();\n ArrayList<Character> al2=new ArrayList<>();\n for(int j=1;j<=4;j++)\n {\n if((i & (1 << (j - 1))) > 0)\n al1.add(ar[j-1]);\n else\n al2.add(ar[j-1]);\n }\n int si1=al1.size();\n char a1[]=new char[si1];\n for(int j=0;j<si1;j++)\n a1[j]=al1.get(j);\n \n int si2=al2.size();\n char a2[]=new char[si2];\n for(int j=0;j<si2;j++)\n a2[j]=al2.get(j);\n \n Arrays.sort(a1);\n Arrays.sort(a2);\n String x1=new String(a1);\n String x2=new String(a2);\n int temp=0;\n temp+=Integer.parseInt(x1);\n temp+=Integer.parseInt(x2);\n sum=Math.min(sum,temp);\n \n }\n return sum;\n }\n}\n```
3
1
['Bitmask', 'Java']
2
minimum-sum-of-four-digit-number-after-splitting-digits
C# LINQ one line 🤪
c-linq-one-line-by-leonenko-3s66
\npublic int MinimumSum(int num) {\n\treturn num.ToString().ToCharArray().OrderBy(x => x).Select( (x, i) => (i < 2 ? 10 : 1) * (x - \'0\')).Sum();\n}\n
leonenko
NORMAL
2022-02-05T16:23:10.990747+00:00
2022-02-05T16:23:23.823761+00:00
199
false
```\npublic int MinimumSum(int num) {\n\treturn num.ToString().ToCharArray().OrderBy(x => x).Select( (x, i) => (i < 2 ? 10 : 1) * (x - \'0\')).Sum();\n}\n```
3
1
[]
1
minimum-sum-of-four-digit-number-after-splitting-digits
C++ : Try all Permutations
c-try-all-permutations-by-praveenchilive-8ctw
```\nint minimumSum(int num) {\n string s=to_string(num);\n int sum=INT_MAX;\n vector v{0,1,2,3};\n do{\n int n1=(s[v[0]]
praveenchiliveri
NORMAL
2022-02-05T16:18:09.262887+00:00
2022-02-05T16:20:03.397286+00:00
306
false
```\nint minimumSum(int num) {\n string s=to_string(num);\n int sum=INT_MAX;\n vector<int> v{0,1,2,3};\n do{\n int n1=(s[v[0]]-\'0\')*10+(s[v[1]]-\'0\');\n int n2=(s[v[2]]-\'0\')*10+(s[v[3]]-\'0\');\n sum=min(sum,n1+n2);\n }\n while(next_permutation(v.begin(),v.end()));\n \n return sum;\n }\n
3
0
[]
1
minimum-sum-of-four-digit-number-after-splitting-digits
✔️ Simple Python and Java Solution with Example for Easy Understanding
simple-python-and-java-solution-with-exa-nhhk
STEPS DONE:\n\n- Sort\n- Pick least possible tens which will be first two and pair with remaining numbers for digits place which will be last two\n\nHavn\'t Und
jiganesh
NORMAL
2022-02-05T16:09:58.993911+00:00
2022-02-05T16:23:23.669933+00:00
340
false
### STEPS DONE:\n\n- Sort\n- Pick least possible tens which will be first two and pair with remaining numbers for digits place which will be last two\n\nHavn\'t Understood !!\n\n### Examples \nIf we have 8759 as a four digit number\n\nTo make a smaller sum we will obviously need smaller numbers\nHence to make the smaller numbers break them into individual digits and sort the numbers\n\nafter sorting we have [5, 7, 8, 9]\nthen we pick a least possible for tens position and max possible for ones position\nlike 5 and 7 for tens position and 9 and 8 for unit digits position\nyou can also pick 5 and 8 and 7 and 9 it doesnt matter as long as your tens digits are least from array\n\n59 + 78 = 137\nThis will be the answer\n\nAnother Example : 4009\nafter sorting [0, 0, 4, 9]\nafter picking 09 + 04 OR 04 + 09 both equals 13\n\nAnother Example : 2932\nafter sorting [2, 2, 3, 9]\nafter picking 29 +23 OR 23 +29 both equals 52\n\nAnother Example : 2675\nafter sorting [2, 5, 6, 7]\nafter picking 27 + 56 OR 57+26 both equals 83\n\n\n### Python Method 1\n\n```python\n\nclass Solution(object):\n \n # TC : O(N)\n # SC : O(N)\n def minimumSum(self, num):\n """\n :type num: int\n :rtype: int\n """ \n a = sorted([i for i in str(num)])\n num1 = a[0]+a[3]\n num2 = a[1]+a[2]\n \n return int(num1)+int(num2) \n```\n### Python Method 2\n\n```python\n\nclass Solution(object):\n \n # TC : O(N)\n # SC : O(N)\n def minimumSum(self, num):\n """\n :type num: int\n :rtype: int\n """\n arr=[]\n \n while num:\n arr.append(num%10)\n num//=10\n return (arr[0]*10+arr[3]) + (arr[1]*10+arr[2])\n```\n \n### Java\n\n```java\nclass Solution {\n public int minimumSum(int num) {\n\n int i = 0;\n int[] arr = new int[4];\n\n while (num > 0) {\n arr[i] = num % 10;\n num = num / 10;\n i++;\n }\n\n Arrays.sort(arr);\n return arr[0]*10 + arr[3] + arr[1]*10 +arr[2]; \n }\n}\n```
3
0
['Python', 'Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Simple Python Solution using Heap
simple-python-solution-using-heap-by-anc-sauq
\nclass Solution:\n def minimumSum(self, num: int) -> int:\n heap, n = [], num\n while n > 0: # Push all digits of num into heap\n h
ancoderr
NORMAL
2022-02-05T16:01:34.974233+00:00
2022-02-05T16:09:01.658750+00:00
515
false
```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n heap, n = [], num\n while n > 0: # Push all digits of num into heap\n heappush(heap, n % 10)\n n = n // 10\n nums1 = nums2 = 0\n while len(heap) > 0: # Use smallest digits to construct each number\n v1 = heappop(heap)\n nums1 = nums1 * 10 + v1\n if len(heap) > 0:\n v2 = heappop(heap)\n nums2 = nums2 * 10 + v2\n return nums1 + nums2\n```
3
2
['Heap (Priority Queue)', 'Python', 'Python3']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Simple Java Code || Beats 100%
simple-java-code-beats-100-by-adityaralh-u4sm
IntuitionApproachComplexity Time complexity: Space complexity: Code
AdityaRalhan
NORMAL
2025-03-26T17:29:59.048073+00:00
2025-03-26T17:29:59.048073+00:00
49
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 [] class Solution { public int minimumSum(int num) { int digits[]=new int[4]; int i=0; while(num>0){ int digit=num%10; digits[i]=digit; num/=10; i++; } Arrays.sort(digits); int num1=digits[0]*10+digits[2]; int num2=digits[1]*10+digits[3]; return num1+num2; } } ```
2
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
basic approach || 0ms || beats 100%
basic-approach-0ms-beats-100-by-professi-ulv9
Code
ProfessionalMonk
NORMAL
2024-12-29T19:04:42.541571+00:00
2024-12-29T19:04:42.541571+00:00
235
false
# Code ```java [] class Solution { public int minimumSum(int num) { int[] arr = new int[4]; int i=0; while(num>0) { arr[i++]=num % 10; num = num/10; } Arrays.sort(arr); int num1 = arr[0] * 10 + arr[2]; int num2 = arr[1] * 10 + arr[3]; return num1 + num2; } } ```
2
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
✅ Easy approach ✅
easy-approach-by-satyam19arya-b70j
TC: O(nlogn)\nSC: O(1)\n\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int> v;\n while(num > 0) {\n int digit = nu
satyam19arya
NORMAL
2024-10-25T22:33:51.101566+00:00
2024-10-25T22:33:51.101592+00:00
198
false
$$TC: O(nlogn)$$\n$$SC: O(1)$$\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int> v;\n while(num > 0) {\n int digit = num % 10;\n v.push_back(digit);\n num /= 10;\n }\n sort(v.begin(), v.end());\n return (v[0] * 10 + v[3]) + (v[1] * 10 + v[2]);\n }\n};\n```
2
0
['Sorting', 'C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
JAVA Easy Solution Beats 100%
java-easy-solution-beats-100-by-jharahul-n5i6
Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve this problem, we need to minimize the sum of two numbers that can be formed by
jharahul3rj
NORMAL
2024-08-15T07:56:05.241374+00:00
2024-08-15T07:56:05.241395+00:00
46
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this problem, we need to minimize the sum of two numbers that can be formed by splitting the digits of the given 4-digit number. The best way to minimize the sum is by ensuring that the digits are distributed evenly between the two numbers we form.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Extract Digits: Start by extracting each digit from the 4-digit number. This can be done by repeatedly taking the remainder of the number divided by 10 and then updating the number by dividing it by 10.\n2. Sort Digits: Once all digits are extracted, sort them in ascending order. This ensures that the smallest digits are used to form the smaller numbers.\n3. Form Numbers: Create two numbers by pairing the smallest and largest remaining digits together. Specifically, form one number using the first and third smallest digits and the other number using the second and fourth smallest digits.\n4. Calculate Sum: Add these two numbers to get the minimum possible sum.\n\n\n\n\n# Complexity\n- Time complexity: O(1)\nThe operations involved (extracting digits, sorting a fixed number of 4 elements) are constant-time operations.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\nWe use a fixed-size array to store digits and a few extra variables, so the space complexity is constant.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumSum(int num) {\n int out[] = new int[4];\n for(int i =0; i<out.length;i++){\n out[i] = num % 10;\n num = num /10;\n }\n Arrays.sort(out);\n int result = ((out[0]*10) + out[2]) + ((out[1]*10) + out[3]);\n return result;\n }\n}\n```
2
0
['Math', 'Greedy', 'Sorting', 'Java']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Easy Solution | Work 100% | Harshad Hiremath
easy-solution-work-100-harshad-hiremath-ulsgb
\n\n# Intuition\nThe problem is to find the minimum sum that can be formed by dividing the digits of a 4-digit number into two two-digit numbers. To minimize th
Harshad_Hiremath
NORMAL
2024-08-06T19:15:48.837145+00:00
2024-08-06T19:17:45.611631+00:00
257
false
![Screenshot 2024-08-07 004408.png](https://assets.leetcode.com/users/images/a0ce837c-475d-4f34-82ad-a0738640e26f_1722971672.7130806.png)\n\n# Intuition\nThe problem is to find the minimum sum that can be formed by dividing the digits of a 4-digit number into two two-digit numbers. To minimize the sum, you need to ensure that the two numbers formed are as small as possible. This can be achieved by sorting the digits and then combining them in a way that ensures minimal sums.\n\n# Approach\nConvert Number to Digits:\nConvert the given 4-digit number to a string to easily extract each digit.\n\nExtract Digits:\nConvert each character of the string back to an integer and store these digits in a vector.\n\nSort Digits:\nSort the vector of digits. Sorting helps in easily forming the smallest possible numbers from the digits.\n\nForm Two Numbers:\nAfter sorting, the smallest two-digit number can be formed by the first and third digits of the sorted list, and the second smallest two-digit number can be formed by the second and fourth digits.\n\nCalculate Minimum Sum:\nAdd these two numbers to get the minimum possible sum.\n\n# Complexity\n- Time complexity:\nThe time complexity is O(logn) due to the sorting operation, where \nn is the number of digits (in this case, n=4). Since n is constant, this is effectively O(1) for this specific problem. Extracting and converting the digits is O(1) as well\n\n- Space complexity:\nThe space complexity is O(1) because the space used does not grow with the input size but is instead constant. This includes the space used for the vector of digits.\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n string str=to_string(num);\n vector<int> v;\n for(char i:str)\n {\n v.push_back(i-\'0\');\n }\n sort(v.begin(),v.end());\n int a=v[0]*10+v[2];\n int b=v[1]*10+v[3];\n return a+b;\n }\n};\n```
2
0
['C++']
1
minimum-sum-of-four-digit-number-after-splitting-digits
easy C++ solution for Minimum Sum of Four Digit Number After Splitting Digits
easy-c-solution-for-minimum-sum-of-four-ym3db
Intuition\nit\'s just a two pointers technique\n\n# Approach\nsort and try to get min member int top left and max at top right ...\n# Complexity\n- Time complex
haroun_brh
NORMAL
2024-05-10T10:12:25.783381+00:00
2024-05-10T10:12:25.783414+00:00
258
false
# Intuition\nit\'s just a two pointers technique\n\n# Approach\nsort and try to get min member int top left and max at top right ...\n# Complexity\n- Time complexity:\nO(n logn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n string temp = to_string(num);\n\n sort(temp.begin(), temp.end());\n\n int left = 0, right = temp.length() - 1;\n\n int sum = 0;\n\n while (left < right) {\n sum += (temp[left] - \'0\') * 10 + (temp[right] - \'0\');\n left++;\n right--;\n }\n\n if (left == right)\n sum += temp[left] - \'0\';\n\n return sum;\n }\n};\n\n```
2
0
['C++']
1
minimum-sum-of-four-digit-number-after-splitting-digits
easy to understand cpp solution || beginner friendly || 0ms runtime
easy-to-understand-cpp-solution-beginner-s0ad
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
akshatmishra__42
NORMAL
2024-04-24T06:30:50.491499+00:00
2024-04-24T06:30:50.491556+00:00
414
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 minimumSum(int num) {\n vector<int>ans;\n int num1=0,num2=0;\n while(num){\n ans.push_back(num%10);\n num=num/10;\n }\n reverse(ans.begin(),ans.end());\n sort(ans.begin(),ans.end());\n num1=ans[0]*10+ans[3];\n num2=ans[1]*10+ans[2];\n\n return num1+num2;\n }\n};\n```
2
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
C++ simple straightforward solution . Beast 100% User with 0ms
c-simple-straightforward-solution-beast-7x895
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
lshigami
NORMAL
2024-01-04T09:22:18.139221+00:00
2024-01-04T09:22:18.139242+00:00
432
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 minimumSum(int num) {\n vector<int>v;\n while(num){\n v.push_back(num%10);\n num/=10;\n }\n sort(v.begin(),v.end());\n return v[0]*10+v[2] + v[1]*10+v[3];\n }\n};\n```
2
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
simple JavaScript solution for beginners 2 line
simple-javascript-solution-for-beginners-yoco
*Bold*# 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\
sabithnk
NORMAL
2024-01-03T12:42:04.115464+00:00
2024-01-03T12:42:04.115534+00:00
566
false
# ****Bold**# 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/**\n * @param {number} num\n * @return {number}\n */\nvar minimumSum = function (num) {\n\n const arr = num.toString().split(\'\').sort()\n return parseInt(arr[0] + arr[2]) + parseInt(arr[1] + arr[3])\n\n\n};\n```
2
0
['JavaScript']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Two Lines DART solution
two-lines-dart-solution-by-mohamed_sadec-85nh
\n# Code\n\nclass Solution {\n int minimumSum(int num) {\n List<String> list = num.toString().split(\'\');\n list.sort();\n return int.parse(list[0]+l
Mohamed_Sadeck
NORMAL
2023-12-31T03:44:03.984875+00:00
2023-12-31T03:44:03.984894+00:00
143
false
\n# Code\n```\nclass Solution {\n int minimumSum(int num) {\n List<String> list = num.toString().split(\'\');\n list.sort();\n return int.parse(list[0]+list[2])+int.parse(list[1]+list[3]);\n }\n}\n```
2
0
['Dart']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Solution using C++
solution-using-c-by-truongtamthanh2004-xzhf
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
truongtamthanh2004
NORMAL
2023-12-02T16:16:48.320946+00:00
2023-12-02T16:16:48.320963+00:00
708
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 minimumSum(int num) {\n vector<int> ans(4, 0);\n for (int i = 0; i < 4; i++)\n {\n ans[i] = num % 10;\n num /= 10;\n }\n ranges::sort(ans);\n return (ans[0] * 10 + ans[2]) + (ans[1] * 10 + ans[3]);\n }\n};\n```
2
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
[]BEATS 100% || JAVA || EASY FOR BEGGINERS
beats-100-java-easy-for-begginers-by-ram-4avm
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
ramuyadav90597
NORMAL
2023-12-01T16:37:38.607628+00:00
2023-12-01T16:37:38.607711+00:00
53
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{\n public int minimumSum(int num)\n {\n int ind=0,num1,num2;\n int arr[] = new int[4];\n while(num!=0){\n arr[ind]=num%10;\n num=num/10;\n ind++;\n }\n Arrays.sort(arr);\n num1=arr[0]*10 +arr[2];\n num2 = arr[1]*10 +arr[3];\n return num1+num2;\n }\n}\n```
2
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Python Easy Solution || 100% ||
python-easy-solution-100-by-rakeshsharma-143x
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
rakeshSharma19
NORMAL
2023-08-08T04:02:13.997680+00:00
2023-08-08T04:02:13.997712+00:00
353
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 minimumSum(self, num: int) -> int:\n arr = list(str(num))\n arr.sort()\n a = int(arr[0]+arr[2])+int(arr[1]+arr[3])\n return a\n```
2
0
['Python3']
0
minimum-sum-of-four-digit-number-after-splitting-digits
JAVA EASY SOLUTION || 100% BEATS || Greedy on Sum
java-easy-solution-100-beats-greedy-on-s-80f7
Approach\n Describe your approach to solving the problem. \nBy greedy on minimum sum,produce a number using first and third element and another element is forme
vijayanvishnu
NORMAL
2023-07-31T11:46:26.169531+00:00
2023-07-31T11:46:26.169547+00:00
40
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nBy greedy on minimum sum,produce a number using first and third element and another element is formed with second and third element.Return the sum of produced elements.\n\n# Complexity\n- Time complexity: $$O(1)$$ , yet it uses only constant running time.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ , yet it uses only constant auxilary space.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumSum(int num) {\n ArrayList<Integer> list = new ArrayList<>();\n int t = num ;\n while(t>0){\n list.add(t%10);\n t/=10;\n }\n Collections.sort(list);\n int first = list.get(0)*10+list.get(2);\n int second = list.get(1)*10+list.get(3);\n return first+second;\n }\n}\n```
2
0
['Greedy', 'Number Theory', 'Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Java beats 100%
java-beats-100-by-anushkagarwal-f5vu
Intuition\n Describe your first thoughts on how to solve this problem. \nInitially we need to convert the number in the form of array so that we can make the pa
anushkagarwal
NORMAL
2023-07-17T08:10:54.348932+00:00
2023-07-17T08:10:54.348955+00:00
195
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInitially we need to convert the number in the form of array so that we can make the pairs of all the digits and check one by one which pairs will give the minimum sum.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n<!-- Describe your approach to solving the problem. -->\nTo convert the num in the array we will make a new array and extract the last digit and store it in the new array and sort the array so as to find the answer greedily.\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{\n public int minimumSum(int num) \n {\n int[] arr = new int[4];\n int i=0;\n while(num>0)\n {\n int a = num%10;\n num = num/10;\n arr[i++] = a;\n }\n Arrays.sort(arr);\n \n int v1 = arr[0]*10 + arr[2];\n int v2 = arr[1]*10 + arr[3];\n return v1+v2;\n }\n}\n```
2
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
solution in java
solution-in-java-by-2manas1-b8uy
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nto make min sum, the 1st elements of both num1 and num2 should be either
2manas1
NORMAL
2023-07-09T18:22:24.218549+00:00
2023-07-09T18:28:42.213289+00:00
691
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nto make min sum, the 1st elements of both num1 and num2 should be either arr[0] or arr[1] after sorting the arr, or we can say the the min elements.\n\nin the code we have converted int to array. now in the array the int is stored as char( ASIC). so suppose you want to access 1st element of array or store it, you need to substract 0. arr[0]-\'0\' to convert it from char to int. if you do arr[0], it will be a char not an int. ex:- 1152 converted to array, in the array it wont be [ 1 1 5 2] but something else.\n\nso we have 2 halves sum1 and sum2. we know 1st and 2nd elements of arr will be the 1st elements of both sum. so we do sum1= num1*10 +num2, we multiply with 10 because we need a 2 digit number.\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 minimumSum(int num) {\n char[] arr= String.valueOf(num).toCharArray();\n/* to make min sum, the 1st elements of both num1 and num2 should be either arr[0] or arr[1] after sorting the arr, or we can say the the min elements. */\n Arrays.sort(arr);\n\n int num1 = (arr[0]-\'0\');\n int num2 = (arr[3]-\'0\');\n int num3= (arr[1]-\'0\');\n int num4 = (arr[2]-\'0\');\n\n int sum1= num1*10 + num2;\n int sum2= num3*10+ num4;\nint finalsum = sum1+sum2;\n return finalsum;\n }\n}\n```
2
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Easy Simple C++ Solution
easy-simple-c-solution-by-priyanshja2003-qoqu
Approach\nHere\'s how the code works:\n\n- It initializes an empty vector arr to store the digits of num.\n\n- The while loop extracts the digits of num one by
priyanshja2003
NORMAL
2023-07-01T09:19:30.092516+00:00
2023-07-01T09:24:14.787404+00:00
995
false
# Approach\nHere\'s how the code works:\n\n- It initializes an empty vector arr to store the digits of num.\n\n- The while loop extracts the digits of num one by one by taking the modulo 10 (num % 10) to get the last digit and pushing it into the vector arr. Then, it divides num by 10 (num = num / 10) to remove the last digit.\n\n- After the loop finishes, the vector arr contains the individual digits of num in reverse order.\n\n- The sort function is used to sort the vector arr in ascending order.\n\n- Two variables, new1 and new2, are initialized to store the values of the rearranged numbers.\n\n- The first rearranged number, new1, is formed by concatenating the smallest digit (arr[0]) with the third smallest digit (arr[2]). The digits are multiplied by 10 to shift their positions accordingly.\n\n- The second rearranged number, new2, is formed by concatenating the second smallest digit (arr[1]) with the fourth smallest digit (arr[3]).\n\n- Finally, the sum of new1 and new2 is returned as the result.\n\n**Note**: The given code assumes that num has 4 digits as given in question.\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int> arr;\n while(num){\n arr.push_back(num%10);\n num = num/10;\n }\n sort(arr.begin(),arr.end());\n int new1=0,new2=0;\n new1 = 10*arr[0]+arr[2];\n new2 = 10*arr[1]+arr[3];\n return new1+new2;\n }\n};\n```
2
0
['Array', 'Math', 'Greedy', 'Sorting', 'C++']
1
minimum-sum-of-four-digit-number-after-splitting-digits
Simple C# solution
simple-c-solution-by-dmitriy-maksimov-9osi
Approach\n- Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers.\n- We can use the two small
dmitriy-maksimov
NORMAL
2023-06-11T01:59:39.723546+00:00
2023-06-11T01:59:39.723578+00:00
255
false
# Approach\n- Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers.\n- We can use the two smallest digits out of the four as the digits found in the tens place respectively.\n- Similarly, we use the final 2 larger digits as the digits found in the ones place.\n\n# Complexity\n- Time complexity: $$O(1)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\npublic class Solution\n{\n public int MinimumSum(int num)\n {\n var sortedDigits = num.ToString().OrderBy(x => x).Select(x => x - \'0\').ToArray();\n var num1 = sortedDigits[0] * 10 + sortedDigits[2];\n var num2 = sortedDigits[1] * 10 + sortedDigits[3];\n\n return num1 + num2;\n }\n}\n```
2
0
['C#']
0
minimum-sum-of-four-digit-number-after-splitting-digits
basic maths, stl
basic-maths-stl-by-nishant_singh07-uriy
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
nishant_singh07
NORMAL
2023-04-27T14:02:13.485480+00:00
2023-04-27T14:02:13.485520+00:00
306
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 minimumSum(int num) {\n string s= to_string(num);\n sort(s.begin(), s.end());\n \n int n1= (s[0]-\'0\')*10 + (s[3]-\'0\');\n int n2= (s[1]-\'0\')*10 + (s[2]-\'0\');\n\n return (n1+n2); \n }\n};\n```
2
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
|| Simple Approach ||
simple-approach-by-ruturajpanditrao777-1mo2
\n\n# Approach\nWe sort the given number.\nThen, to minimize the sum formed by nums1 and nums2 as required,\nIt is obvious that we should generate 2 digit 2 num
ruturajpanditrao777
NORMAL
2023-04-27T05:09:41.518861+00:00
2023-06-14T07:20:30.490134+00:00
289
false
\n\n# Approach\nWe sort the given number.\nThen, to minimize the sum formed by nums1 and nums2 as required,\nIt is obvious that we should generate 2 digit 2 numbers as their sum would be lesser than a 3 digit number and a 1 digit number.\n\nHence to generate the minimum sum,\nTo minimize the numbers created,\nWe club together the smallest digit followed by greatest digit.\nWe club together the second smallest digit number followed by second greatest digit.\n\nSTEPS :\n1> Sort the Number Digits.\n2> Generate the nums1 as 1st Digit followed by 4th Digit.\n3> Generate the nums2 as 2nd Digit followed by 3d Digit.\n4> Return the minimum sum, as nums1 + nums2.\n\nFor example,\n2932\n-> 2239\nWe make the numbers as 29 and 23. Which give the Minimum Sum.\n\n4009\n-> 0049\nWe make the numbers 09 and 04. Which give the Minimum Sum.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity Analysis\n# Time Complexity: O(NlogN)\nAlmost Constant Time Algorithm.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Space complexity: O(1)\nAlmost Constant Space Algorithm.\n<!-- Add your space cmathomplexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) \n {\n string nums = to_string(num);\n sort(nums.begin(),nums.end());\n char nums1 = nums[0];\n char nums2 = nums[1];\n char nums3 = nums[2];\n char nums4 = nums[3];\n\n string ans1 = "";\n ans1 += nums1;\n ans1 += nums4;\n string ans2 = "";\n ans2 += nums2;\n ans2 += nums3;\n\n return stoi(ans1) + stoi(ans2);\n\n }\n};\n```
2
0
['Math', 'C++']
2
minimum-sum-of-four-digit-number-after-splitting-digits
CPP||100%BEATS
cpp100beats-by-sampurnathakur-aj89
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
SampurnaThakur
NORMAL
2023-03-31T16:46:45.209074+00:00
2023-03-31T16:46:45.209112+00:00
283
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\nclass Solution {\npublic:\n int minimumSum(int num) {\n //array for store the retrived element\n vector<int> nums;\n //retriving one by one number of num \n while(num>0)\n {\n nums.push_back(num%10);\n num=num/10;\n }\n //here sorting the array\n sort(nums.begin(),nums.end());\n return nums[0]*10+nums[2]+nums[1]*10+nums[3];\n }\n};\n```
2
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Simple Java Solution🔥 || 0ms runtime || Beats 100% 🔥
simple-java-solution-0ms-runtime-beats-1-yy3w
Stats\n- RunTime: 0ms (Beats 100%)\n\n# Code\n\npublic int minimumSum(int num) {\n int digitsArr [] = new int[4], index = 0;\n\n while (num != 0) {\n
Abhinav-Bhardwaj
NORMAL
2023-03-19T16:49:42.055452+00:00
2023-04-12T19:30:48.472406+00:00
795
false
# Stats\n- **RunTime**: 0ms (Beats 100%)\n\n# Code\n```\npublic int minimumSum(int num) {\n int digitsArr [] = new int[4], index = 0;\n\n while (num != 0) {\n digitsArr[index++] = num % 10;\n num /= 10;\n }\n\n Arrays.sort(digitsArr);\n\n return ((digitsArr[0] * 10 + digitsArr[3]) + (digitsArr[1] * 10 + digitsArr[2]));\n}\n\n```\n<br/>\n<br/>\n<br/>\n\nAuthor :- [*Abhinav Bhardwaj*](https://abhinavbhardwaj.in)
2
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
C++ easy solution.
c-easy-solution-by-aloneguy-l7q3
\n\n# Code\n\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int>v;\n while(num!=0){\n v.push_back(num%10);\n
aloneguy
NORMAL
2023-03-13T05:38:46.947249+00:00
2023-03-13T05:38:46.947285+00:00
9
false
\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int>v;\n while(num!=0){\n v.push_back(num%10);\n num/=10;\n }\n sort(v.begin(),v.end());\n return (v[0]*10+v[1]*10+v[2]+v[3]);\n }\n};\n```
2
0
['Math', 'C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
c# Accepted : Easy to understand
c-accepted-easy-to-understand-by-rhazem1-d5xk
\npublic class Solution {\n public int MinimumSum(int num) {\n List<int> number=new();\n while(num>0){\n number.Add(num%10);\n
rhazem13
NORMAL
2023-02-15T13:08:24.524048+00:00
2023-02-15T13:08:24.524087+00:00
1,523
false
```\npublic class Solution {\n public int MinimumSum(int num) {\n List<int> number=new();\n while(num>0){\n number.Add(num%10);\n num/=10;\n }\n number.Sort();\n return (number[0]*10+number[3])+(number[1]*10+number[2]);\n }\n}\n```
2
0
[]
0
minimum-sum-of-four-digit-number-after-splitting-digits
Python 3 solution
python-3-solution-by-akshat3821-i9pf
Intuition\n Describe your first thoughts on how to solve this problem. \nSimple loopless approach using Mathematics\n\n# Approach\n Describe your approach to so
akshat3821
NORMAL
2023-02-07T07:39:24.168282+00:00
2023-07-30T03:29:35.472751+00:00
1,717
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimple loopless approach using Mathematics\n\n# Approach\n<!-- Describe your approach to solving the problem. -->After we convert the given 4 digit number type and sort it, the addition of (first digit,last digit) with (second digit,third digit) gives us least combo.\n\n# Complexity\n- Time complexity:\n```\nO(nlogn)\n```\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n num = str(num)\n num = sorted(list(num))\n num = str(num)\n print(num)\n list1 = list()\n list1.append((num[2]+num[17]))\n list1.append((num[7]+num[12]))\n return (int(list1[0])+int(list1[1]))\n```
2
0
['Python3']
3
minimum-sum-of-four-digit-number-after-splitting-digits
0ms runtime || Beats 100 %
0ms-runtime-beats-100-by-shristha-f9pi
\n\n# Code\n\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int>digit;\n while(num>0){\n digit.push_back(num%10);\n
Shristha
NORMAL
2023-01-25T15:15:40.074258+00:00
2023-01-25T15:15:40.074307+00:00
1,543
false
\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int>digit;\n while(num>0){\n digit.push_back(num%10);\n num/=10;\n } \n sort(digit.begin(),digit.end());\n return (digit[0]*10+digit[3])+(digit[1]*10+digit[2]);\n }\n};\n```
2
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
Java Easiest Solution
java-easiest-solution-by-janhvi__28-b9d8
\n# Code\n\nclass Solution {\n public int minimumSum(int num) {\n int[] nums = new int[4];\n for (int i = 0; num != 0; ++i) {\n nums
Janhvi__28
NORMAL
2023-01-15T13:05:32.265575+00:00
2023-01-15T13:05:32.265621+00:00
407
false
\n# Code\n```\nclass Solution {\n public int minimumSum(int num) {\n int[] nums = new int[4];\n for (int i = 0; num != 0; ++i) {\n nums[i] = num % 10;\n num /= 10;\n }\n Arrays.sort(nums);\n return 10 * (nums[0] + nums[1]) + nums[2] + nums[3];\n }\n}\n```
2
0
['Java']
0
minimum-sum-of-four-digit-number-after-splitting-digits
c++ || sorting ||easy to understand
c-sorting-easy-to-understand-by-jauliadh-enob
\n# Complexity\n- Time complexity:\no(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n int minimumSum(int num)\n {\n in
jauliadhikari2012
NORMAL
2023-01-13T17:45:10.270873+00:00
2023-01-13T17:45:10.270912+00:00
1,170
false
\n# Complexity\n- Time complexity:\no(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumSum(int num)\n {\n int digit = num;vector<int> v;\n while(digit!=0)\n {\n int temp = digit%10;\n v.push_back(temp);\n digit = digit/10;\n }\n sort(v.begin(),v.end());\n\n int num1 = v[0]*10 + v[2];\n int num2 = v[1]*10 + v[3];\n\n int sum = num1 + num2;\n return sum;\n }\n};\n\n\n```
2
0
['C++']
0
minimum-sum-of-four-digit-number-after-splitting-digits
✅ [Java/C++] 100% Solution using Greedy (Minimum Sum of Four Digit Number After Splitting Digits)
javac-100-solution-using-greedy-minimum-qf5nk
Complexity\n- Time complexity: O(1)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Ja
arnavsharma2711
NORMAL
2023-01-08T15:31:34.091322+00:00
2023-01-09T17:01:09.550365+00:00
2,137
false
# Complexity\n- Time complexity: $$O(1)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Java Code\n```\nclass Solution {\n public int minimumSum(int num) {\n int[] digits = new int[4];\n int i=0;\n while(i<=3)\n {\n digits[i++] = num%10;\n num/=10;\n }\n Arrays.sort(digits);\n // digits[0] at ten\'s place and digits[2] at one\'s place makes the first number\n // digits[1] at ten\'s place and digits[3] at one\'s place makes the second number\n return digits[0]*10+digits[2]+digits[1]*10+digits[3];\n }\n}\n```\n# C++ Code\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n int digits[4];\n int i=0;\n while(i<=3)\n {\n digits[i++] = num%10;\n num/=10;\n }\n sort(digits,digits+4);\n // digits[0] at ten\'s place and digits[2] at one\'s place makes the first number\n // digits[1] at ten\'s place and digits[3] at one\'s place makes the second number\n return digits[0]*10+digits[2]+digits[1]*10+digits[3];\n }\n};\n```
2
0
['Math', 'Greedy', 'Sorting', 'C++', 'Java']
1
minimum-sum-of-four-digit-number-after-splitting-digits
C++ 4 lines just sort and one swap
c-4-lines-just-sort-and-one-swap-by-user-mu3g
\nclass Solution {\npublic:\n int minimumSum(int num) {\n string x = to_string(num);\n sort(x.begin(), x.end());\n swap(x[2], x[1]);\n
user5976fh
NORMAL
2022-12-24T02:59:31.056033+00:00
2022-12-24T02:59:31.056072+00:00
619
false
```\nclass Solution {\npublic:\n int minimumSum(int num) {\n string x = to_string(num);\n sort(x.begin(), x.end());\n swap(x[2], x[1]);\n return stoi(x.substr(0, 2)) + stoi(x.substr(2, 2));\n }\n};\n```
2
0
[]
0
minimum-sum-of-four-digit-number-after-splitting-digits
C++|| easy solution || 0 ms || easy-understanding
c-easy-solution-0-ms-easy-understanding-4rxl6
\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int>v;\n while(num!=0){\n v.push_back(num%10);\n num=num
arunava_42
NORMAL
2022-11-17T13:40:13.256768+00:00
2022-11-17T13:40:13.256833+00:00
9
false
```\nclass Solution {\npublic:\n int minimumSum(int num) {\n vector<int>v;\n while(num!=0){\n v.push_back(num%10);\n num=num/10;\n }\n sort(v.begin(),v.end());\n int n1=v[0]*10+v[3];\n int n2=v[1]*10+v[2];\n return n1+n2;\n }\n};\n```\nIf you like the approach,please upvote the solution.
2
0
[]
0
minimum-sum-of-four-digit-number-after-splitting-digits
C++ || 0ms || Easy Solution
c-0ms-easy-solution-by-ayushk28-bybq
Here, what we do first is to seperate all the digits in the number, and store them in an array of size 4.\nTo do this we take the modulo of the number with 10 t
AyushK28
NORMAL
2022-11-08T12:46:08.877566+00:00
2022-11-09T04:08:01.790593+00:00
29
false
Here, what we do first is to seperate all the digits in the number, and store them in an array of size 4.\nTo do this we take the modulo of the number with 10 to get the last digit, and then divide the number by 10, and run the loop again to get the next digit.\n\nNow we will sort the array to arrange all the digits obtained in an non-decreasing order.\n\nAfter sorting the digits, we have to make 2, 2 digit numbers, as we know if we make a 3 digit number and a one digit number, it\'s sum will always be more than that of sum of 2, 2 digit numbers.\nSince we want the minimum possible sum, the 10s place digits of those 2 numbers must be minimum.\nSo the first 2 elements of our sorted array are the 10s digit of our number and the reamaining 2 elements are the ones digit. Combination of 10s place digit with Ones place digit doesn\'t matter here, as both will give exact same sum.\n\n```\nclass Solution {\npublic:\n int minimumSum(int num) {\n int arr[4]; // Declaring an Array of size 4\n for(int i =0; i<4; i++) // Running a loop to fill array with digits of num\n {\n arr[i] = num%10; // Taking the last digit and inserting it in the array\n num /= 10;\n }\n sort(arr, arr + 4); // Sorting the array\n\t\t// Returning the sum of 2 numbers.\n return (arr[0]*10 + arr[2] + arr[1]*10 + arr[3]);\n }\n};\n```
2
1
['C', 'Sorting', 'C++']
0
implement-magic-dictionary
Easy 14 lines Java solution, HashMap
easy-14-lines-java-solution-hashmap-by-s-aqyu
For each word in dict, for each char, remove the char and put the rest of the word as key, a pair of index of the removed char and the char as part of value lis
shawngao
NORMAL
2017-09-10T03:13:29.010000+00:00
2018-10-26T05:52:05.437036+00:00
25,451
false
1. For each word in ```dict```, for each char, remove the char and put the rest of the word as key, a pair of index of the removed char and the char as ```part of``` value list into a map. e.g.\n"hello" -> {"ello":[[0, 'h']], "hllo":[[1, 'e']], "helo":[[2, 'l'],[3, 'l']], "hell":[[4, 'o']]}\n2. During search, generate the keys as in step 1. When we see there's pair of same index but different char in the value array, we know the answer is true. e.g.\n"healo" when remove ```a```, key is "helo" and there is a pair [2, 'l'] which has same index but different char. Then the answer is true;\n\n```\nclass MagicDictionary {\n\n Map<String, List<int[]>> map = new HashMap<>();\n /** Initialize your data structure here. */\n public MagicDictionary() {\n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n for (String s : dict) {\n for (int i = 0; i < s.length(); i++) {\n String key = s.substring(0, i) + s.substring(i + 1);\n int[] pair = new int[] {i, s.charAt(i)};\n \n List<int[]> val = map.getOrDefault(key, new ArrayList<int[]>());\n val.add(pair);\n \n map.put(key, val);\n }\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) {\n for (int i = 0; i < word.length(); i++) {\n String key = word.substring(0, i) + word.substring(i + 1);\n if (map.containsKey(key)) {\n for (int[] pair : map.get(key)) {\n if (pair[0] == i && pair[1] != word.charAt(i)) return true;\n }\n }\n }\n return false;\n }\n}\n```
146
8
[]
20
implement-magic-dictionary
Python, without *26 factor in complexity
python-without-26-factor-in-complexity-b-pjtu
A word 'apple' has neighbors '*pple', 'a*ple', 'ap*le', 'app*e', 'appl*'. When searching for a target word like 'apply', we know that a necessary condition is
awice
NORMAL
2017-09-10T04:19:36.009000+00:00
2017-09-10T04:19:36.009000+00:00
11,444
false
A word `'apple'` has neighbors `'*pple', 'a*ple', 'ap*le', 'app*e', 'appl*'`. When searching for a target word like `'apply'`, we know that a necessary condition is a neighbor of `'apply'` is a neighbor of some source word in our magic dictionary. If there is more than one source word that does this, then at least one of those source words will be different from the target word. Otherwise, we need to check that the source doesn't equal the target.\n\n```python\nclass MagicDictionary(object):\n def _candidates(self, word):\n for i in xrange(len(word)):\n yield word[:i] + '*' + word[i+1:]\n \n def buildDict(self, words):\n self.words = set(words)\n self.near = collections.Counter(cand for word in words\n for cand in self._candidates(word))\n\n def search(self, word):\n return any(self.near[cand] > 1 or \n self.near[cand] == 1 and word not in self.words\n for cand in self._candidates(word))\n```
108
5
[]
7
implement-magic-dictionary
[C++] Easy solution using trie
c-easy-solution-using-trie-by-jakhar1205-vot2
\nstruct T{\n bool end=false;\n T* c[26];\n T(){\n end=false;\n memset(c, NULL, sizeof(c));\n }\n};\nclass MagicDictionary {\npublic:\
jakhar1205
NORMAL
2021-08-02T17:51:04.712762+00:00
2021-08-13T09:41:54.994615+00:00
4,272
false
```\nstruct T{\n bool end=false;\n T* c[26];\n T(){\n end=false;\n memset(c, NULL, sizeof(c));\n }\n};\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n T* root;\n MagicDictionary() {\n root = new T();\n }\n \n void buildDict(vector<string> dict) {\n int n=dict.size();\n // build the trie\n for(int i=0;i<n;i++)\n {\n T* node=root;\n string word=dict[i];\n for(int j=0;j<word.size();j++)\n {\n if(!node->c[dict[i][j]-\'a\'])\n node->c[dict[i][j]-\'a\']=new T();\n node=node->c[dict[i][j]-\'a\'];\n }\n node->end=true;\n }\n }\n \n bool helper(string word)\n {\n T* node=root;\n int n=word.size();\n for(int i=0;i<n;i++)\n {\n if(!node->c[word[i]-\'a\'])\n return false;\n node=node->c[word[i]-\'a\'];\n }\n return node->end;\n }\n \n bool search(string sword) {\n int n=sword.size();\n string word=sword;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<26;j++)\n {\n if(\'a\'+j==sword[i])\n continue;\n word[i]=\'a\'+j;\n if(helper(word))\n return true;\n }\n word[i]=sword[i];\n }\n return false;\n }\n};\n```\n\nPlease upvote if it helps you in any way :)
54
1
[]
2
implement-magic-dictionary
Easiest JAVA with Trie, no need to count the number of changes
easiest-java-with-trie-no-need-to-count-2to4g
Below is my accepted java code.\nFirst build a trie tree, and in search(String word) function, we just edit every character from 'a' to 'z' and search the new s
fionafang
NORMAL
2017-09-11T23:17:41.475000+00:00
2018-09-21T19:25:44.540007+00:00
13,743
false
Below is my accepted java code.\nFirst build a trie tree, and in search(String word) function, we just edit every character from 'a' to 'z' and search the new string. \n (This process is like "word ladder")\n\n````\nclass MagicDictionary {\n class TrieNode {\n TrieNode[] children = new TrieNode[26];\n boolean isWord;\n public TrieNode() {}\n }\n TrieNode root;\n /** Initialize your data structure here. */\n public MagicDictionary() {\n root = new TrieNode();\n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n for (String s : dict) {\n TrieNode node = root;\n for (char c : s.toCharArray()) {\n if (node.children[c - 'a'] == null) {\n node.children[c - 'a'] = new TrieNode();\n }\n node = node.children[c - 'a'];\n }\n node.isWord = true;\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) {\n char[] arr = word.toCharArray();\n for (int i = 0; i < word.length(); i++) {\n for (char c = 'a'; c <= 'z'; c++) {\n if (arr[i] == c) {\n continue;\n }\n char org = arr[i];\n arr[i] = c;\n if (helper(new String(arr), root)) {\n return true;\n }\n arr[i] = org;\n }\n }\n return false;\n }\n public boolean helper(String s, TrieNode root) {\n TrieNode node = root;\n for (char c : s.toCharArray()) {\n if (node.children[c - 'a'] == null) {\n return false;\n }\n node = node.children[c - 'a'];\n }\n return node.isWord;\n }\n}\n````
44
7
['Trie', 'Java']
14
implement-magic-dictionary
Python intuitive solution using dictionary
python-intuitive-solution-using-dictiona-jsgs
The basic idea here is very simple: we construct a dictionary, whose key is the length of the given words, and the value is a list containing the words with the
goldenalcheese
NORMAL
2017-09-15T02:48:25.047000+00:00
2017-09-15T02:48:25.047000+00:00
4,344
false
The basic idea here is very simple: we construct a dictionary, whose key is the length of the given words, and the value is a list containing the words with the same length specified in the key. And when we search a word (say word "hello") in the magic dictionary, we only need to check those words in dic[len("hellow")], ( named candi in my code). Simple and quite intuitive but beat 90% :-)\n\n```\nclass MagicDictionary(object):\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.wordsdic={}\n\n def buildDict(self, dict):\n """\n Build a dictionary through a list of words\n :type dict: List[str]\n :rtype: void\n """\n for i in dict:\n self.wordsdic[len(i)]=self.wordsdic.get(len(i),[])+[i]\n\n def search(self, word):\n """\n Returns if there is any word in the trie that equals to the given word after modifying exactly one character\n :type word: str\n :rtype: bool\n """\n for candi in self.wordsdic.get(len(word),[]):\n countdiff=0\n for j in range(len(word)):\n if candi[j]!=word[j]:\n countdiff+=1\n if countdiff==1:\n return True\n return False\n \n \n\n\n# Your MagicDictionary object will be instantiated and called as such:\n# obj = MagicDictionary()\n# obj.buildDict(dict)\n# param_2 = obj.search(word)\n```
37
1
[]
5
implement-magic-dictionary
Python Trie Way
python-trie-way-by-ipeq1-u47m
\nclass TrieNode(object):\n def __init__(self):\n self.isAend = False\n self.contains = {}\nclass MagicDictionary(object):\n def __init__(se
ipeq1
NORMAL
2017-09-15T00:26:16.011000+00:00
2017-09-15T00:26:16.011000+00:00
3,132
false
```\nclass TrieNode(object):\n def __init__(self):\n self.isAend = False\n self.contains = {}\nclass MagicDictionary(object):\n def __init__(self):\n self.root = TrieNode()\n def addWord(self, word):\n r = self.root\n for chr in word:\n if chr not in r.contains:\n r.contains[chr] = TrieNode()\n r = r.contains[chr]\n r.isAend = True\n\n def findWord(self, remain, r, word):\n if not word:\n return True if remain == 0 and r.isAend else False\n for key in r.contains.keys():\n if key == word[0]:\n if self.findWord(remain, r.contains[key], word[1:]):\n return True\n elif remain == 1:\n if self.findWord(0, r.contains[key], word[1:]):\n return True\n return False\n def buildDict(self, dict):\n for word in dict:\n self.addWord(word)\n def search(self, word):\n return self.findWord(1, self.root, word)\n```
33
0
[]
6
implement-magic-dictionary
C++ trie solution
c-trie-solution-by-cychung-0vts
updated 2020/09/15\nThe original code can\'t pass OJ anymore. Please see updated code below.\n\nclass Node{\npublic:\n vector<Node*> next;\n bool isWord;\
cychung
NORMAL
2018-11-07T22:41:52.280591+00:00
2020-09-15T08:07:35.971388+00:00
3,676
false
`updated 2020/09/15`\nThe original code can\'t pass OJ anymore. Please see updated code below.\n```\nclass Node{\npublic:\n vector<Node*> next;\n bool isWord;\n Node(){\n isWord = false;\n next = vector<Node*>(26, NULL);\n }\n};\n\nclass Trie{\nprivate:\n Node* root;\npublic:\n Trie(){\n root = new Node();\n }\n void insert(string s){\n Node* cur = root;\n for(char c: s){\n if(cur->next[c - \'a\'] == NULL)\n cur->next[c - \'a\'] = new Node();\n cur = cur->next[c - \'a\'];\n }\n cur->isWord = true;\n }\n \n bool find(string s){\n Node* cur = root;\n for(char c: s){\n if(cur->next[c - \'a\'] == NULL)\n return false;\n cur = cur->next[c - \'a\'];\n }\n return cur->isWord;\n }\n};\n\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {\n trie = new Trie();\n }\n \n /** Build a dictionary through a list of words */\n void buildDict(vector<string> dict) {\n for(string s: dict){\n trie->insert(s);\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n bool search(string word) {\n for(int i = 0; i < word.size(); i++){\n for(int j = 0; j < 26; j++){\n char c = j + \'a\';\n if(c == word[i]) continue;\n char oriChar = word[i];\n word[i] = c;\n if(trie->find(word))\n return true;\n word[i] = oriChar;\n }\n }\n return false;\n }\nprivate:\n Trie* trie;\n};\n ```\n \n`updated 2020/09/15`\nThe OJ has changed the time limit, so my original code can\'t pass.\nI updated my code to do dfs to optimize.\n```\nclass Node{\npublic:\n vector<Node*> next;\n bool isWord;\n Node(){\n isWord = false;\n next = vector<Node*>(26, NULL);\n }\n};\n\nclass Trie{\nprivate:\n Node* root;\npublic:\n Trie(){\n root = new Node();\n }\n void insert(string s){\n Node* cur = root;\n for(char c: s){\n if(cur->next[c - \'a\'] == NULL)\n cur->next[c - \'a\'] = new Node();\n cur = cur->next[c - \'a\'];\n }\n cur->isWord = true;\n }\n \n bool find(string s, int cur_idx, int change = 0, Node* cur = NULL) {\n if (!cur) cur = root;\n if (cur_idx == s.size()) return cur->isWord && change == 1;\n Node* next = cur->next[s[cur_idx] - \'a\'];\n if (change == 1) {\n if (!next) return false;\n else return find(s, cur_idx + 1, 1, next);\n } else {\n if (next && find(s, cur_idx + 1, 0, next)) return true;\n for (int i = 0; i < 26; i++) {\n if (s[cur_idx] == \'a\' + i) continue;\n if (cur->next[i] && find(s, cur_idx + 1, 1, cur->next[i])) return true;\n }\n return false;\n }\n }\n};\n\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {\n trie = new Trie();\n }\n \n /** Build a dictionary through a list of words */\n void buildDict(vector<string> dict) {\n for(string s: dict){\n trie->insert(s);\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n bool search(string word) {\n return trie->find(word, 0);\n }\nprivate:\n Trie* trie;\n};\n```\n
30
2
[]
14
implement-magic-dictionary
Clean Java Code with Trie
clean-java-code-with-trie-by-aimhighfly7-h2de
\nclass MagicDictionary {\n class Trie{\n boolean isEnd;\n Map<Character, Trie> children;\n Trie(){\n children = new HashMap(
aimhighfly7859
NORMAL
2018-07-10T23:02:11.093355+00:00
2018-10-18T09:00:26.838444+00:00
2,223
false
```\nclass MagicDictionary {\n class Trie{\n boolean isEnd;\n Map<Character, Trie> children;\n Trie(){\n children = new HashMap();\n }\n }\n Trie root;\n \n public MagicDictionary() {\n root = new Trie();\n }\n \n public void buildDict(String[] dict) {\n for(String s : dict){\n Trie curr = root;\n for(char c : s.toCharArray()){\n if(!curr.children.containsKey(c)){\n curr.children.put(c, new Trie());\n }\n curr = curr.children.get(c);\n }\n curr.isEnd = true;\n }\n }\n \n public boolean search(String word) {\n return search(word, 0, root, false);\n }\n public boolean search(String word, int i, Trie node, boolean flag){\n if(i < word.length()){\n if(node.children.containsKey(word.charAt(i))){\n if(search(word, i+1, node.children.get(word.charAt(i)), flag)){\n return true;\n }\n }\n if(!flag){\n for(char c: node.children.keySet()){\n if(c!= word.charAt(i) && search(word, i+1, node.children.get(c), true)) return true;\n }\n }\n return false;\n }\n return flag && node.isEnd;\n }\n}\n```
30
0
[]
2
implement-magic-dictionary
66ms Prefix Tree (Trie) Java with Explanation
66ms-prefix-tree-trie-java-with-explanat-7o4p
Thought\nWe could build a trie using word in dicts. If two words differ by one character only, they will be within the branches regardless of the mismatched cha
gracemeng
NORMAL
2018-10-04T00:56:52.405548+00:00
2018-10-15T01:27:18.139722+00:00
1,464
false
**Thought**\nWe could build a trie using word in dicts. If two words differ by one character only, they will be within the branches regardless of the mismatched character.\n```\nFor example, dict = ["ooo", "ooa"] and search("oxo"), they have one character mismatched, \n\no - o [mismatched here, cntMismatched = 1] - a [mismatched here, cntMismatched = 2, backtrack]\n\t\t\t\t - o - exhausted [cntMismatched = 1, return true]\n \n```\n**Code**\n```\n /** Initialize your data structure here. */\n \n private static Node root;\n public MagicDictionary() {\n root = new Node(); \n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n buildTrie(dict);\n }\n \n private void buildTrie(String[] dict) {\n Node ptr;\n for (String word : dict) {\n ptr = root;\n for (char ch : word.toCharArray()) {\n int order = ch - \'a\';\n if (ptr.children[order] == null)\n ptr.children[order] = new Node();\n ptr = ptr.children[order];\n }\n ptr.isWordEnd = true;\n }\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) { \n return dfs(0, word, root, 0);\n }\n \n private boolean dfs(int curId, String word, Node parentPtr, int cntMismatched) {\n \n if (cntMismatched > 1) {\n return false;\n }\n \n if (curId == word.length()) { \n return parentPtr.isWordEnd && cntMismatched == 1;\n }\n\n \n for (int i = 0; i < 26; i++) { \n int order = word.charAt(curId) - \'a\';\n if (parentPtr.children[i] == null)\n continue; \n if (order != i) {\n if (dfs(curId + 1, word, parentPtr.children[i], cntMismatched + 1))\n return true;\n } else {\n if (dfs(curId + 1, word, parentPtr.children[i], cntMismatched))\n return true;\n }\n } \n \n return false;\n }\n \n class Node {\n \n Node[] children;\n boolean isWordEnd;\n \n public Node() {\n children = new Node[26];\n isWordEnd = false;\n }\n } \n```\n**I appreciate your VOTE UP (\u25B0\u2579\u25E1\u2579\u25B0)**
21
0
[]
2
implement-magic-dictionary
Simple Python solution
simple-python-solution-by-otoc-pcix
Please see and vote for my solutions for\n208. Implement Trie (Prefix Tree)\n1233. Remove Sub-Folders from the Filesystem\n1032. Stream of Characters\n211. Add
otoc
NORMAL
2019-06-26T04:30:43.404423+00:00
2022-08-16T04:30:24.744315+00:00
1,391
false
Please see and vote for my solutions for\n[208. Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/discuss/320224/Simple-Python-solution)\n[1233. Remove Sub-Folders from the Filesystem](https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/409075/standard-python-prefix-tree-solution)\n[1032. Stream of Characters](https://leetcode.com/problems/stream-of-characters/discuss/320837/Standard-Python-Trie-Solution)\n[211. Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/discuss/319361/Simple-Python-solution)\n[676. Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/discuss/320197/Simple-Python-solution)\n[677. Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/discuss/320237/Simple-Python-solution)\n[745. Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/discuss/320712/Different-Python-solutions-with-thinking-process)\n[425. Word Squares](https://leetcode.com/problems/word-squares/discuss/320916/Easily-implemented-Python-solution%3A-Backtrack-%2B-Trie)\n[472. Concatenated Words](https://leetcode.com/problems/concatenated-words/discuss/322444/Python-solutions%3A-top-down-DP-Trie)\n[212. Word Search II](https://leetcode.com/problems/word-search-ii/discuss/319071/Standard-Python-solution-with-Trie-%2B-Backtrack)\n[336. Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/discuss/316960/Different-Python-solutions%3A-brute-force-dictionary-Trie)\n\n```\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.isEnd = False\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n \n def insert(self, word):\n node = self.root\n for char in word:\n if char not in node.children:\n node.children[char] = TrieNode()\n node = node.children[char]\n node.isEnd = True\n\nclass MagicDictionary:\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.trie = Trie()\n\n def buildDict(self, words: List[str]) -> None:\n """\n Build a dictionary through a list of words\n """\n for w in words:\n self.trie.insert(w)\n\n def search(self, word: str) -> bool:\n """\n Returns if there is any word in the trie that equals to the given word after modifying exactly one character\n """\n def dfs(node, i, word):\n if i == len(word):\n return node.isEnd and self.modified\n if self.modified:\n if word[i] in node.children:\n return dfs(node.children[word[i]], i + 1, word)\n else:\n return False\n else:\n for c in node.children:\n self.modified = c != word[i]\n if dfs(node.children[c], i + 1, word):\n return True\n return False\n \n self.modified = False\n return dfs(self.trie.root, 0, word)\n```
20
2
[]
1
implement-magic-dictionary
Easy Java Solution
easy-java-solution-by-ydeng365-bfmo
Some thoughts:\nIt may not be necessary to implement the trie for this problem.\nThe time complexity and space complexity are the same.\nAnd in some cases, trie
ydeng365
NORMAL
2017-09-10T03:01:04.099000+00:00
2018-10-24T08:39:05.524609+00:00
2,590
false
Some thoughts:\nIt may not be necessary to implement the trie for this problem.\nThe time complexity and space complexity are the same.\nAnd in some cases, trie version might be even slower? \n\n```\nclass MagicDictionary {\n\n HashSet<String> dictSet;\n \n /** Initialize your data structure here. */\n public MagicDictionary() {\n dictSet = new HashSet<>();\n }\n \n /** Build a dictionary through a list of words */\n public void buildDict(String[] dict) {\n dictSet = new HashSet<String>();\n for(String word : dict)\n dictSet.add(word);\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n public boolean search(String word) {\n char[] chars = word.toCharArray();\n for(int i = 0; i < chars.length; i++){\n char ch = chars[i];\n for (char c = 'a'; c <= 'z'; c++){\n if (c != ch){\n chars[i] = c;\n if (dictSet.contains(new String(chars)))\n return true;\n }\n }\n chars[i] = ch;\n }\n return false;\n }\n}\n```
16
3
[]
2
implement-magic-dictionary
Efficient Python Trie solution, without traversing all characters (a-z) at each step
efficient-python-trie-solution-without-t-bcc2
\nclass MagicDictionary(object):\n\n def __init__(self):\n self.trie = {}\n\n def buildDict(self, dict):\n for word in dict: \n n
aditya74
NORMAL
2017-09-10T03:45:05.993000+00:00
2018-10-15T15:09:45.751082+00:00
2,006
false
```\nclass MagicDictionary(object):\n\n def __init__(self):\n self.trie = {}\n\n def buildDict(self, dict):\n for word in dict: \n node = self.trie \n for letter in word: \n if letter not in node: \n node[letter] = {}\n node = node[letter] \n node[None] = None \n\n def search(self, word):\n def find(node, i, mistakeAllowed): \n if i == len(word):\n if None in node and not mistakeAllowed: \n return True\n return False \n if word[i] not in node: \n return any(find(node[letter], i+1, False) for letter in node if letter) if mistakeAllowed else False \n \n if mistakeAllowed: \n return find(node[word[i]], i+1, True) or any(find(node[letter], i+1, False) for letter in node if letter and letter != word[i])\n return find(node[word[i]], i+1, False)\n \n return find(self.trie, 0, True) \n\n```
15
1
[]
2
implement-magic-dictionary
Python 3 Trie + DFS Solution w/ Explanation
python-3-trie-dfs-solution-w-explanation-fvw9
The idea here is to use a Trie and a depth first search, similar to LeetCode 211: https://leetcode.com/problems/design-add-and-search-words-data-structure.\n\nW
async-await
NORMAL
2021-10-30T16:43:04.615788+00:00
2021-10-30T17:40:11.748575+00:00
1,156
false
The idea here is to use a Trie and a depth first search, similar to LeetCode 211: https://leetcode.com/problems/design-add-and-search-words-data-structure.\n\nWe define a TrieNode to use for this algorithm. I choose to specify that a node is explicitly a terminal node for a word with ```is_end``` but you may opt to simply add a child with "#". Whatever works for you.\n\nThe idea behind this algorithm is that we have to try the change at every possible place, even if the character matches because we could end up with the case that we never change anything and end up with the string we originally searched for, which is not allowed given the example test cases (because we MUST change 1 character). We will keep track of this with a variable called ```modifications``` which has an initial value of 1 and represents the modifications we are allowed to make.\n\nWe kick off our DFS at the root of the Trie. For each invocation of DFS, the algorithm proceeds as follows:\n\n+ 1). Check that modifications is > 0. If modifications = 1, then we haven\'t used a modification. If modifications = 0, then we have used our one allowed modification. If modifications is less than 0, then we have used more than one modification and this path is invalid as it violates the problem statement that only allows us one character change.\n+ 2). If our search word is empty, that means we have reached the end of the Trie and we need to check whether or not we have a valid answer here. A valid answer here is one where we have used our one allowed change AND the node we are at is the terminal node for a word.\n+ 3). Once those checks are done, if we still have work to do, then we iterate over the characters at this level in the Trie. \n\t+ If the character is equal to the first character of the string we are searching, then call dfs recursively with that next node, slice the first character off the string, and keep modifications untouched as we have not made a change.\n\t+ If the character is not equal, then we do the same as in the previous step except this time we call the recursive DFS function with modifications - 1 as we are using our one change allowed to skip the current character.\n\n\nI\'m not 100% sure on the time complexity of this algorithm. Perhaps someone can help in the comments below.\n\n```\nclass TrieNode:\n def __init__(self, char):\n self.char = char\n self.children = {}\n self.is_end = False\n \nclass MagicDictionary:\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.trie = TrieNode("#")\n\n def add_word(self, word):\n root = self.trie\n \n for char in word:\n if char not in root.children:\n root.children[char] = TrieNode(char)\n \n root = root.children[char]\n \n root.is_end = True\n \n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n self.add_word(word)\n \n def search(self, searchWord: str) -> bool:\n return self.dfs(self.trie, searchWord, 1)\n \n def dfs(self, node, word, modifications):\n if modifications < 0:\n return False\n \n if not word:\n return not modifications and node.is_end\n \n for child in node.children:\n if child == word[0]:\n if self.dfs(node.children[word[0]], word[1:], modifications):\n return True\n else:\n if self.dfs(node.children[child], word[1:], modifications - 1):\n return True \n```
13
0
['Depth-First Search', 'Trie', 'Python']
1
implement-magic-dictionary
C++, unordered_set
c-unordered_set-by-zestypanda-f3x9
The solution is to use hash table to save the dictionary. For each word to search, generate all possible candidates and verify whether it is in the dictionary.\
zestypanda
NORMAL
2017-09-10T03:04:27.319000+00:00
2017-09-10T03:04:27.319000+00:00
2,451
false
The solution is to use hash table to save the dictionary. For each word to search, generate all possible candidates and verify whether it is in the dictionary.\nFor the follow-up question, we should implement a trie rather than use hash table. Trie uses less space and more efficient for a large dictionary. \n```\nclass MagicDictionary {\npublic:\n /** Initialize your data structure here. */\n MagicDictionary() {\n \n }\n \n /** Build a dictionary through a list of words */\n void buildDict(vector<string> dict) {\n for (string &s:dict) words.insert(s);\n }\n \n /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n bool search(string word) {\n for (int i = 0; i < word.size(); i++) {\n char c = word[i];\n for (int j = 0; j < 26; j++) {\n if (c == j+'a') continue;\n word[i] = j+'a';\n if (words.count(word)) return true;\n }\n word[i] = c;\n }\n return false;\n }\nprivate:\n unordered_set<string> words;\n};\n```
12
2
[]
2
implement-magic-dictionary
C++ Tries method
c-tries-method-by-fdsm_lhn-c0ah
``` class MagicDictionary { class trienode{ public: vector<trienode *> alphabets = vector<trienode *> (26, nullptr); bool is_end=false;
fdsm_lhn
NORMAL
2018-10-21T18:33:45.594610+00:00
2018-10-21T18:33:45.594654+00:00
819
false
``` class MagicDictionary { class trienode{ public: vector<trienode *> alphabets = vector<trienode *> (26, nullptr); bool is_end=false; }; trienode *root; bool search(trienode *cur, string &word, int index, bool flag){ if(index == word.length()){ if(flag && cur->is_end) return true; return false; } int right = word[index]-'a'; for(int i=0;i<26;i++){ if(cur->alphabets[i]){ if(right!=i && !flag){ if(search(cur->alphabets[i], word, index+1,true)) return true; }else{ if(right==i && search(cur->alphabets[i], word, index+1,flag)) return true; } } } return false; } public: MagicDictionary() { root = new trienode(); } /** Build a dictionary through a list of words */ void buildDict(vector<string> dict) { trienode *start; for(auto word:dict){ start = root; for(auto c:word){ if(start->alphabets[c - 'a']){ start = start->alphabets[c - 'a']; }else{ start->alphabets[c - 'a'] = new trienode(); start = start->alphabets[c - 'a']; } } start-> is_end = true; } } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ bool search(string word) { return search(root, word, 0, false); } }; ``` Tries data structure and backstracking search, very easy to understand.
10
0
[]
0
implement-magic-dictionary
Python 97.27% speed | Hashmap only | Simple code
python-9727-speed-hashmap-only-simple-co-ip4b
For each word, length is the key. For each searchWord, only need to check the words with same length\n\n\nclass MagicDictionary:\n\n def __init__(self):\n
gulugulugulugulu
NORMAL
2022-03-31T21:16:34.951705+00:00
2022-04-01T21:19:23.311909+00:00
1,161
false
For each word, length is the key. For each searchWord, only need to check the words with same length\n\n```\nclass MagicDictionary:\n\n def __init__(self):\n self.myDict = defaultdict(set)\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n n = len(word)\n self.myDict[n].add(word)\n\n def search(self, searchWord: str) -> bool:\n n = len(searchWord)\n if n not in self.myDict: return False\n \n def diff(word1, word2):\n count = 0\n for i in range(len(word1)):\n if word1[i] != word2[i]:\n count += 1 \n if count > 1:\n return count\n return count\n \n \n for word in self.myDict[n]:\n if diff(word, searchWord) == 1:\n return True\n return False\n```
8
0
['Hash Table', 'Python', 'Python3']
2
implement-magic-dictionary
[EASY UNDERSTANDING][C++]
easy-understandingc-by-rajat_gupta-gi5b
\nclass MagicDictionary {\npublic:\n\n unordered_set<string> set;\n\t\n MagicDictionary(){\n }\n \n void buildDict(vector<string> dictionary){\n
rajat_gupta_
NORMAL
2020-12-02T06:12:43.887954+00:00
2020-12-02T06:12:43.888003+00:00
714
false
```\nclass MagicDictionary {\npublic:\n\n unordered_set<string> set;\n\t\n MagicDictionary(){\n }\n \n void buildDict(vector<string> dictionary){\n for(string str: dictionary)\n set.insert(str);\n }\n \n bool search(string searchWord){\n for(string s: set){\n if(s.size()==searchWord.size()){\n int cnt=0;\n for(int i=0;i<s.size();i++){\n if(s[i]!=searchWord[i]) cnt++;\n }\n if(cnt==1) return true;\n }\n }\n return false;\n }\n\t\n};\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n
8
0
['C', 'C++']
3
implement-magic-dictionary
Java easy, no tries and hashes, beats 99%
java-easy-no-tries-and-hashes-beats-99-b-bsqz
I am not familiar with advanced data structures, but it seems we can solve it without them:\n\nclass MagicDictionary {\n private String[] data;\n\n public
sdedovich
NORMAL
2021-06-29T16:27:44.456319+00:00
2021-09-09T12:23:17.131020+00:00
566
false
I am not familiar with advanced data structures, but it seems we can solve it without them:\n```\nclass MagicDictionary {\n private String[] data;\n\n public void buildDict(String[] dictionary) {\n this.data = dictionary;\n }\n\n public boolean search(String searchWord) {\n for (String element : data) {\n if (onlyOneCharDifferent(element, searchWord)) {\n return true;\n }\n }\n\n return false;\n }\n\n private boolean onlyOneCharDifferent(String element, String searchWord) {\n if (element.length() != searchWord.length()) {\n return false;\n }\n\n boolean onlyOneCharDifferent = false;\n\n for (int i = 0; i < element.length(); i++) {\n boolean differentChars = element.charAt(i) != searchWord.charAt(i);\n\n if (differentChars && !onlyOneCharDifferent) {\n onlyOneCharDifferent = true;\n } else if (differentChars) {\n onlyOneCharDifferent = false;\n break;\n }\n }\n\n return onlyOneCharDifferent;\n }\n}\n```
7
0
['Array', 'Java']
3
implement-magic-dictionary
Java DFS + Trie, extendable for modifying n characters
java-dfs-trie-extendable-for-modifying-n-zr5n
\nclass MagicDictionary {\n \n class TrieNode {\n Map<Character, TrieNode> children = new HashMap<>();\n boolean isEnd = false;\n }\n
rocket_ggy
NORMAL
2021-02-21T00:06:04.268057+00:00
2021-02-21T00:11:13.743169+00:00
652
false
```\nclass MagicDictionary {\n \n class TrieNode {\n Map<Character, TrieNode> children = new HashMap<>();\n boolean isEnd = false;\n }\n \n public TrieNode root;\n\n public MagicDictionary() {\n this.root = new TrieNode(); \n }\n \n //build a regular trie\n public void buildDict(String[] dictionary) {\n for (String s: dictionary) {\n TrieNode node = this.root;\n for (char c : s.toCharArray()) {\n if (!node.children.containsKey(c)) {\n node.children.put(c, new TrieNode());\n }\n node = node.children.get(c);\n }\n node.isEnd = true;\n }\n }\n \n public boolean search(String searchWord) {\n TrieNode node = this.root;\n //alter exact 1 char, so put 1\n return magicSearch(searchWord, node, 1);\n }\n \n public boolean magicSearch(String searchWord, TrieNode node, int diff) {\n if (diff == 0) {\n return strictSearch(node, searchWord);\n }\n \n char[] searchWordArray = searchWord.toCharArray();\n for (int i = 0; i<searchWordArray.length; i++) {\n char c = searchWordArray[i];\n \n //Option 1: change the current char\n for (char alter : node.children.keySet()) {\n if (alter != c) {\n if (magicSearch(searchWord.substring(i+1), node.children.get(alter), diff - 1)) {\n return true;\n }\n } \n }\n \n //Option 2: do not change the current char\n if (!node.children.containsKey(c)) {\n break; // return false if we can\'t change the current char but but the char does not belong to the node\'s children\n } \n \n node = node.children.get(c);\n }\n return false;\n }\n \n public boolean strictSearch(TrieNode node, String word) {\n for (char c: word.toCharArray()) {\n if (!node.children.containsKey(c)) {\n return false;\n } \n node = node.children.get(c);\n }\n return node.isEnd;\n }\n}\n```
7
0
['Depth-First Search', 'Trie', 'Recursion', 'Java']
1