title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
655
7
```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n mapping={\'I\':1,\'V\':5,\'X\':10,\'L\':50,\'C\':100,\'D\':500,\'M\':1000}\n s=s.replace(\'IV\',\'IIII\').replace(\'IX\',\'VIIII\').replace(\'XL\',\'XXXX\').replace(\'XC\',\'LXXXX\') \\\n .replace(\'CD\',\'CCCC\').replace(\'CM\',\'DCCCC\')\n ans=0\n for c in s:\n ans+=mapping[c]\n return ans \n \n```
1,272
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
17,260
62
\n# \uD83D\uDDEF\uFE0FComplexity :-\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# \uD83D\uDDEF\uFE0FCode :-\n```\nclass Solution {\npublic:\n int romanToInt(string s) {\n int res=0;\n s+=\' \';\n for(int i=0;i<s.size();){\n if(s[i]==\'I\' && s[i+1]==\'V\') { res+=4; i+=2;}\n else if(s[i]==\'I\' && s[i+1]==\'X\') { res+=9; i+=2;}\n else if(s[i]==\'I\') { res++; i++;}\n else if(s[i]==\'V\') { res+=5; i++;}\n else if(s[i]==\'X\' && s[i+1]==\'L\') { res+=40; i+=2;}\n else if(s[i]==\'X\' && s[i+1]==\'C\') { res+=90; i+=2;}\n else if(s[i]==\'X\') { res+=10; i++;} \n else if(s[i]==\'L\') { res+=50; i++;}\n else if(s[i]==\'C\' && s[i+1]==\'M\') { res+=900; i+=2;}\n else if(s[i]==\'C\' && s[i+1]==\'D\') { res+=400; i+=2;}\n else if(s[i]==\'C\') { res+=100; i++;}\n else if(s[i]==\'D\') { res+=500; i++;}\n else if(s[i]==\'M\') { res+=1000; i++;}\n else if(s[i]==\' \') break;\n }\n return res;\n }\n};\n```\n# ***Please Upvote if it helps :) \u2764\uFE0F***\n\n
1,273
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
601
12
\n# Code\n```\nclass Solution {\n public int romanToInt(String s) {\n HashMap<Character,Integer> map = new HashMap<>();\n map.put(\'I\',1);\n map.put(\'V\',5);\n map.put(\'X\',10);\n map.put(\'L\',50);\n map.put(\'C\',100);\n map.put(\'D\',500);\n map.put(\'M\',1000);\n\n int n = s.length();\n int ans = 0;\n\n for(int i = 0; i < n; i++){\n if(i < n-1 && map.get(s.charAt(i)) < map.get(s.charAt(i+1))){\n ans = ans - map.get(s.charAt(i));\n } else{\n ans = ans + map.get(s.charAt(i));\n }\n\n }\n System.out.println(map); //Checking the output\n return ans;\n }\n}\n```\n\n\n![images.jpeg]()
1,276
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
1,630
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\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```\nclass Solution {\n public int romanToInt(String s) {\n int sum = 0;\n int i = 0;\n for (i = 0; i < s.length() - 1; i++) {\n switch (s.charAt(i)) {\n case \'M\':\n sum += 1000;\n break;\n case \'D\':\n sum += 500;\n break;\n case \'C\':\n switch (s.charAt(i + 1)) {\n case \'D\':\n sum += 400;\n i++;\n break;\n case \'M\':\n sum += 900;\n i++;\n break;\n\n default:\n sum += 100;\n }\n\n break;\n case \'L\':\n sum += 50;\n break;\n case \'X\':\n switch (s.charAt(i + 1)) {\n case \'L\':\n sum += 40;\n i++;\n break;\n case \'C\':\n sum += 90;\n i++;\n break;\n\n default:\n sum += 10;\n }\n break;\n case \'V\':\n sum += 5;\n break;\n case \'I\':\n switch (s.charAt(i + 1)) {\n case \'V\':\n sum += 4;\n i++;\n break;\n case \'X\':\n sum += 9;\n i++;\n break;\n\n default:\n sum += 1;\n }\n\n break;\n }\n }\n if (i >= s.length()) {\n return sum;\n }\n switch (s.charAt(i)) {\n case \'M\':\n sum += 1000;\n break;\n case \'D\':\n sum += 500;\n break;\n case \'C\':\n sum += 100;\n\n break;\n case \'L\':\n sum += 50;\n break;\n case \'X\':\n sum += 10;\n\n break;\n case \'V\':\n sum += 5;\n break;\n case \'I\':\n\n sum += 1;\n\n break;\n }\n\n return sum;\n }\n}\n\n```
1,279
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
3,309
16
### C#,Java,Python3,JavaScript different solution with explanation\n**\u2B50[]()\u2B50**\n\n**\uD83E\uDDE1See next question solution - [Zyrastory-Longest Common Prefix]()**\n\nIf you got any problem about the explanation or you need other programming language solution, please feel free to leave your comment.\n\n**Thanks!**
1,281
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
3,383
12
# Code\n```\nconst romans = {\n I: 1,\n V: 5,\n X: 10,\n L: 50,\n C: 100,\n D: 500,\n M: 1000\n};\n\nfunction romanToInt(s: string): number {\n const numbers: number[] = s.split(\'\').map(v => romans[v]);\n return numbers.reduce((acc, num, index) => num < numbers[index + 1] ?? 0 ? acc - num : acc + num, 0);\n};\n```
1,288
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
348
8
```var romanToInt = function(s) {\n const roman = {\n "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C": 100, "D" : 500, "M" : 1000\n }\n let sum = 0\n for (let i=s.length-1;i >= 0; i--){\n sum = roman[s[i]] < roman[s[i+1]] ? sum - roman[s[i]] : sum + roman[s[i]]\n }\n return sum\n};\n````
1,292
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
3,658
12
```\nclass Solution {\npublic:\n int romanToInt(string s) {\n int sum = 0;\n int size = s.size();\n \n \n for(int i=0; i<size; i++)\n {\n if(s[i] == \'I\')\n {\n sum +=1;\n }\n else if(s[i] == \'V\')\n {\n if(i>0 && s[i-1] == \'I\')\n {\n sum = sum +5 -2;\n }\n else\n {\n sum = sum+5;\n }\n }\n else if(s[i] == \'X\')\n {\n if(i>0 && s[i-1] == \'I\')\n {\n sum = sum +10 -2;\n }\n else\n {\n sum = sum+10;\n }\n }\n else if(s[i] == \'L\')\n {\n if(i>0 && s[i-1] == \'X\')\n {\n sum = sum +50-20;\n }\n else\n {\n sum = sum+50;\n }\n }\n else if(s[i] == \'C\')\n {\n if(i>0 && s[i-1] == \'X\')\n {\n sum = sum +100-20;\n }\n else\n {\n sum = sum+100;\n }\n }\n else if(s[i] == \'D\')\n {\n if(i>0 && s[i-1] == \'C\')\n {\n sum = sum +500-200;\n }\n else\n {\n sum = sum+500;\n }\n }\n else if(s[i] == \'M\')\n {\n if(i>0 && s[i-1] == \'C\')\n {\n sum = sum +1000-200;\n }\n else\n {\n sum = sum+1000;\n }\n }\n \n }\n \n \n return sum;\n }\n};\n```
1,296
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
971
5
```\nclass Solution {\npublic:\n int romanToInt(string s) {\n int i=0,value=0;\n unordered_map<char,int>mp; \n mp[\'I\']=1,mp[\'V\']=5,mp[\'X\']=10,mp[\'L\']=50,mp[\'C\']=100,mp[\'D\']=500,mp[\'M\']=1000; \n while(i<s.length()){\n if(i<s.length()-1 && mp[s[i]] < mp[s[i+1]]){\n value+=mp[s[i+1]]-mp[s[i]];\n i=i+2;\n }\n else{\n value+=mp[s[i]];\n i++;\n }\n }\n return value; \n }\n};\n```
1,297
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.
Hash Table,Math,String
Easy
Problem is simpler to solve by working the string from back to front and using a map.
1,516
30
class Solution {\n public int romanToInt(String s) {\n Map<Character,Integer>map=new HashMap<>();\n map.put(\'I\', 1);\n map.put(\'V\', 5);\n map.put(\'X\', 10);\n map.put(\'L\', 50);\n map.put(\'C\', 100);\n map.put(\'D\', 500);\n map.put(\'M\', 1000);\n \n \n int result=map.get(s.charAt(s.length()-1));\n \n for(int i=s.length()-2;i>=0;i--){\n if(map.get(s.charAt(i))<map.get(s.charAt(i+1))){\n result-=map.get(s.charAt(i));\n }else{\n result+=map.get(s.charAt(i));\n }\n }\n return result;\n }\n}\n\'\'\'\n.****Plz upvote if you find it USEFUL. May you will get all you deserve .Hard work will payOff
1,299
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
207,518
1,587
# Please UPVOTE\uD83D\uDE0A\n![image.png]()\n\nThis code implements the longestCommonPrefix function that takes a list of strings v as input and returns the longest common prefix of all the strings. Here is an explanation of how the code works:\n\n1. Initialize an empty string ans to store the common prefix.\n2. Sort the input list v lexicographically. This step is necessary because the common prefix should be common to all the strings, so we need to find the common prefix of the first and last string in the sorted list.\n3. Iterate through the characters of the first and last string in the sorted list, stopping at the length of the shorter string.\n4. If the current character of the first string is not equal to the current character of the last string, return the common prefix found so far.\n5. Otherwise, append the current character to the ans string.\n6. Return the ans string containing the longest common prefix.\n\nNote that the code assumes that the input list v is non-empty, and that all the strings in v have at least one character. If either of these assumptions is not true, the code may fail.\n# Python3\n```\nclass Solution:\n def longestCommonPrefix(self, v: List[str]) -> str:\n ans=""\n v=sorted(v)\n first=v[0]\n last=v[-1]\n for i in range(min(len(first),len(last))):\n if(first[i]!=last[i]):\n return ans\n ans+=first[i]\n return ans \n\n```\n# C++\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& v) {\n string ans="";\n sort(v.begin(),v.end());\n int n=v.size();\n string first=v[0],last=v[n-1];\n for(int i=0;i<min(first.size(),last.size());i++){\n if(first[i]!=last[i]){\n return ans;\n }\n ans+=first[i];\n }\n return ans;\n }\n};\n```\n# Java \n```\nclass Solution {\n public String longestCommonPrefix(String[] v) {\n StringBuilder ans = new StringBuilder();\n Arrays.sort(v);\n String first = v[0];\n String last = v[v.length-1];\n for (int i=0; i<Math.min(first.length(), last.length()); i++) {\n if (first.charAt(i) != last.charAt(i)) {\n return ans.toString();\n }\n ans.append(first.charAt(i));\n }\n return ans.toString();\n }\n}\n```\n![image.png]()
1,300
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
129,786
1,437
\n# Approach\nThis code is used to find the longest common prefix of an array of strings, which is defined as the longest string that is a prefix of all the strings in the array. By sorting the array and then comparing the first and last elements, the code is able to find the common prefix that would be shared by all strings in the array.\n\n1. Sort the elements of an array of strings called "strs" in lexicographic (alphabetical) order using the Arrays.sort(strs) method.\n2. Assign the first element of the sorted array (the lexicographically smallest string) to a string variable s1.\n3. Assign the last element of the sorted array (the lexicographically largest string) to a string variable s2.\n4. Initialize an integer variable idx to 0.\n5. Start a while loop that continues while idx is less than the length of s1 and s2.\n6. Within the while loop, check if the character at the current index in s1 is equal to the character at the same index in s2. If the characters are equal, increment the value of idx by 1.\n7. If the characters are not equal, exit the while loop.\n8. Return the substring of s1 that starts from the first character and ends at the idxth character (exclusive).\n\n\n\n# Complexity\n- Time complexity:\n1. Sorting the array of strings takes O(Nlog(N)) time. This is because most of the common sorting algorithms like quicksort, mergesort, and heapsort have an average time complexity of O(Nlog(N)).\n2. Iterating over the characters of the first and last strings takes O(M) time. This is because the code compares the characters of the two strings until it finds the first mismatch.\n\nTherefore, the total time complexity is O(Nlog(N) + M).\n\n\n\n\n- Space complexity:\nThe space used by the two string variables s1 and s2 is proportional to the length of the longest string in the array. Therefore, the space complexity is O(1) as it does not depend on the size of the input array.\n\n# Reason for Sorting \n\nThe reason why we sort the input array of strings and compare the first and last strings is that the longest common prefix of all the strings must be a prefix of the first string and a prefix of the last string in the sorted array. This is because strings are ordered based on their alphabetical order (Lexicographical order).\nFor example, consider the input array of strings {"flower", "flow", "flight"}. After sorting the array, we get {"flight", "flow", "flower"}. The longest common prefix of all the strings is "fl", which is located at the beginning of the first string "flight" and the second string "flow". Therefore, by comparing the first and last strings of the sorted array, we can easily find the longest common prefix.\n\n# Code\n```\nclass Solution {\n public String longestCommonPrefix(String[] strs) {\n Arrays.sort(strs);\n String s1 = strs[0];\n String s2 = strs[strs.length-1];\n int idx = 0;\n while(idx < s1.length() && idx < s2.length()){\n if(s1.charAt(idx) == s2.charAt(idx)){\n idx++;\n } else {\n break;\n }\n }\n return s1.substring(0, idx);\n }\n}\n```\n![upvote.jpeg]()\n
1,301
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
8,277
70
![image.png]()\n\n# Intuition\nTo find the longest common prefix among an array of strings, we can compare the characters of all strings from left to right until we encounter a mismatch. The common prefix will be the characters that are the same for all strings until the first mismatch.\n\n\n# Approach\n- If the input array strs is empty, return an empty string because there is no common prefix.\n\n- Initialize a variable prefix with an initial value equal to the first string in the array strs[0].\n\n- Iterate through the rest of the strings in the array strs starting from the second string (index 1).\n\n- For each string in the array, compare its characters with the characters of the prefix string.\n\n- While comparing, if we find a mismatch between the characters or if the prefix becomes empty, return the current value of prefix as the longest common prefix.\n\n- After iterating through all strings, return the final value of prefix as the longest common prefix.\n\n# Complexity\n- Time complexity:\nO(n * m), where n is the number of strings in the array, and m is the length of the longest string.\n\n- Space complexity:\nO(m), where m is the length of the longest string, as we store the prefix string.\n\n# Java\n```\npublic class Solution {\n public String longestCommonPrefix(String[] strs) {\n if (strs == null || strs.length == 0) return "";\n String prefix = strs[0];\n for (String s : strs)\n while (s.indexOf(prefix) != 0)\n prefix = prefix.substring(0, prefix.length() - 1);\n return prefix;\n }\n}\n```\n\n# Python\n```\nclass Solution:\n def longestCommonPrefix(self, strs):\n if not strs:\n return ""\n prefix = strs[0]\n for string in strs[1:]:\n while string.find(prefix) != 0:\n prefix = prefix[:-1]\n if not prefix:\n return ""\n return prefix\n```\n\n\n# C++\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& strs) {\n if (strs.empty()) return "";\n string prefix = strs[0];\n for (string s : strs)\n while (s.find(prefix) != 0)\n prefix = prefix.substr(0, prefix.length() - 1);\n return prefix;\n }\n};\n\n```\n\n![ejw70Xlg.png]()\n
1,302
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
44,088
234
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& strs) {\n sort(strs.begin(),strs.end());\n int a=strs.size();\n string n=strs[0],m=strs[a-1],ans="";\n for(int i=0;i<n.size();i++){\n if(n[i]==m[i]){ans+=n[i];}\n else break;\n }\n return ans;\n \n }\n};\nDo UPVOTE if you like\n```
1,308
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
40,952
556
```\nclass Solution {\n public String longestCommonPrefix(String[] strs) {\n String prefix = strs[0];\n for(int index=1;index<strs.length;index++){\n while(strs[index].indexOf(prefix) != 0){\n prefix=prefix.substring(0,prefix.length()-1);\n }\n }\n return prefix;\n }\n}\n\n/*\nPLEASE UPVOTE IF IT HELPS YOU! THANK YOU!\nRecommend to dry run along with the example.\n\nWorking:\n1)Take the first(index=0) string in the array as prefix.\n2)Iterate from second(index=1) string till the end.\n3)Use the indexOf() function to check if the prefix is there in the strs[i] or not.\nIf the prefix is there the function returns 0 else -1.\n4)Use the substring function to chop the last letter from prefix each time the function return -1.\n\neg:\nstrs=["flower", "flow", "flight"]\nprefix=flower\nindex=1\n while(strs[index].indexOf(prefix) != 0) means while("flow".indexOf("flower")!=0)\n Since flower as a whole is not in flow, it return -1 and prefix=prefix.substring(0,prefix.length()-1) reduces prefix to "flowe"\n Again while(strs[index].indexOf(prefix) != 0) means while("flow".indexOf("flowe")!=0)\n Since flowe as a whole is not in flow, it return -1 and prefix=prefix.substring(0,prefix.length()-1) reduces prefix to "flow"\n Again while(strs[index].indexOf(prefix) != 0) means while("flow".indexOf("flow")!=0)\n Since flow as a whole is in flow, it returns 0 so now prefix=flow\nindex=2\n while(strs[index].indexOf(prefix) != 0) means while("flight".indexOf("flow")!=0)\n Since flow as a whole is not in flight, it return -1 and prefix=prefix.substring(0,prefix.length()-1) reduces prefix to "flo"\n Again while(strs[index].indexOf(prefix) != 0) means while("flight".indexOf("flo")!=0)\n Since flo as a whole is not in flight, it return -1 and prefix=prefix.substring(0,prefix.length()-1) reduces prefix to "fl"\n Again while(strs[index].indexOf(prefix) != 0) means while("flight".indexOf("fl")!=0)\n Since fl as a whole is in flight, it returns 0 so now prefix=fl\nindex=3, for loop terminates and we return prefix which is equal to fl\n*/\n\n```
1,309
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
1,133
9
\n\nThis solution is the <b>vertical scanning</b> approach that is discussed in the official solution, slightly modified for Python. The idea is to scan the the first character of every word, then the second character, etc. until a mismatch is found. At that point, we return a slice of the string which is the longest common prefix.\n\nThis is superior to horizontal scanning because even if a very short word is included in the array, the algorithm won\'t do any extra work scanning the longer words and will still end when the end of the shortest word is reached.\n\n# Code\n```\nclass Solution(object):\n def longestCommonPrefix(self, strs):\n if len(strs) == 0:\n return ""\n\n base = strs[0]\n for i in range(len(base)):\n for word in strs[1:]:\n if i == len(word) or word[i] != base[i]:\n return base[0:i]\n\n return base\n \n```
1,310
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
42,824
257
The longest common prefix is common to all the strings. So, we can fix one string and check the common prefix of this string with other strings. The minimum such length is found and the answer is the substring of the fixed string starting from 0 to the length of the above such minimum.\nHere, I have fixed 0th string and checked other strings with this. \n**Full Code:**\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& s) {\n int ans = s[0].length(), n = s.size();\n for(int i=1; i<n; i++){\n int j = 0;\n while(j<s[i].length() && s[i][j]==s[0][j])j++;\n ans = min(ans, j);\n }\n return s[0].substr(0, ans);\n }\n};\n```\n**Incase you found the post useful, please give it an upvote.**
1,311
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
2,161
11
# 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(object):\n def longestCommonPrefix(self, strs):\n if not strs:\n return "" # If the input list is empty, there is no common prefix.\n\n # Find the shortest string in the list (the minimum length determines the common prefix length).\n min_len = min(len(s) for s in strs)\n \n common_prefix = ""\n for i in range(min_len):\n # Compare the current character of all strings with the character at the same position in the first string.\n current_char = strs[0][i]\n for string in strs:\n if string[i] != current_char:\n return common_prefix # If characters don\'t match, return the common prefix found so far.\n \n common_prefix += current_char # If characters match, add the character to the common prefix.\n \n return common_prefix\n\n```
1,312
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
61,368
559
```class Solution {\n public String longestCommonPrefix(String[] strs) {\n if (strs == null || strs.length == 0)\n return "";\n \n Arrays.sort(strs);\n String first = strs[0];\n String last = strs[strs.length - 1];\n int c = 0;\n while(c < first.length())\n {\n if (first.charAt(c) == last.charAt(c))\n c++;\n else\n break;\n }\n return c == 0 ? "" : first.substring(0, c);\n }\n}
1,317
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
21,552
145
```\n public String longestCommonPrefix(String[] strs) {\n if(strs.length==0) return "";\n String prefix=strs[0];\n for(int i=1;i<strs.length;i++){\n while(strs[i].indexOf(prefix)!=0){\n prefix=prefix.substring(0,prefix.length()-1);\n }\n \n }\n return prefix;\n \n \n }\n//Please upvote
1,319
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
2,614
7
# Approach\nThe given code implements the `longestCommonPrefix` method, which takes an array of strings `strs` as input and returns the longest common prefix among the strings. Here is an explanation of the approach used in the code:\n\n1. Initialize a variable `ans` with the first string in the array `strs`. This is done assuming that the first string is the initial common prefix.\n\n2. Initialize an empty string `sub` to store the temporary common prefix between `ans` and the current string being checked.\n\n3. Iterate through the remaining strings in the `strs` array starting from the second string.\n\n4. For each string, iterate through its characters and compare them with the characters at the corresponding positions in `ans`. The inner loop runs until either the end of the current string or the end of `ans`, whichever is shorter.\n\n5. If the characters at the current position in both `ans` and the current string are the same, append that character to the `sub` string.\n\n6. If the characters at the current position are not the same, break out of the inner loop because it means that the common prefix ends at this point.\n\n7. Update `ans` to be equal to `sub`, which contains the common prefix found so far.\n\n8. Reset `sub` to an empty string for the next iteration.\n\n9. After all the strings have been processed, the value of `ans` will be the longest common prefix among all the strings.\n\n10. Finally, return the `ans` string as the result.\n\nNote: The code assumes that the input `strs` array is not empty and contains at least one string.\n\n# Complexity\n- Time complexity:\nThe time complexity of the given code is O(N * M), where N is the length of the input array strs and M is the length of the shortest string in strs\n\n- Space complexity:\nThe space complexity of the code is O(M), where M is the length of the shortest string in strs.\n\n# Code\n```\nclass Solution {\n public String longestCommonPrefix(String[] strs) { \n String ans = strs[0];\n String sub = "";\n \n for (int i = 1; i < strs.length; i++) {\n \n for (int j = 0; j < Math.min(ans.length(), strs[i].length()); j++) {\n\n if (ans.charAt(j) == strs[i].charAt(j)) {\n sub += ans.charAt(j);\n }\n else{\n break;\n }\n }\n ans = sub;\n sub = "";\n }\n return ans;\n }\n}\n```
1,323
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
36,978
105
# Intuition\nCompare each letter of each word to check if they match, and add them to an empty string until you hit a character that doesn\'t match. Return the string obtained so far.\n\n# Approach\nInitialize an empty string. Zip the list, so you get the first characters of each word together in a tuple, the second letters in another tuple, and so on. Convert each such tuple into a set, and check if the length of the set is 1 - to understand if the elements were same (as sets store only 1 instance of a repeated element). If the length of the set is 1, add the first element of the tuple (any element is fine, as all elements are same but we take the first element just to be cautious) to the empty string. If the length of a set is not 1, return the string as is. Finally, return the string obtained thus far.\n\n# Complexity\n- Time complexity:\n\n\n- Space complexity:\n\n\n# Code\n```\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n res = ""\n for a in zip(*strs):\n if len(set(a)) == 1: \n res += a[0]\n else: \n return res\n return res\n \n```
1,326
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
125,525
803
```\n def longestCommonPrefix(self, strs):\n """\n :type strs: List[str]\n :rtype: str\n """\n if not strs:\n return ""\n shortest = min(strs,key=len)\n for i, ch in enumerate(shortest):\n for other in strs:\n if other[i] != ch:\n return shortest[:i]\n return shortest \n```
1,331
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
54,096
371
The code below is very much self explanatory. \n1. We first sort the array of strings.\n2. Then, we choose the first and last string in the array. `[They are supposed to be the most different among all the pairs of strings in the sorted array]`\n3. We just compare how many common characters match from index `i = 0` of these two strings.\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& str) {\n int n = str.size();\n if(n==0) return "";\n \n string ans = "";\n sort(begin(str), end(str));\n string a = str[0];\n string b = str[n-1];\n \n for(int i=0; i<a.size(); i++){\n if(a[i]==b[i]){\n ans = ans + a[i];\n }\n else{\n break;\n }\n }\n \n return ans;\n \n }\n};\n```\n\n
1,338
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
2,349
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncomparing the characters of the smallest string in the given string array!!\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution {\n public String longestCommonPrefix(String[] strs) {\n StringBuffer ans=new StringBuffer();\n if(strs.length==1)\n {\n return strs[0];\n }\n // FINDING THE SMALLEST STRING\n int min=strs[0].length();\n \n int index=0;\n for(int i=0;i<strs.length;i++)\n {\n if(strs[i].length()<min)\n {\n min=strs[i].length();\n index=i;\n }\n }\n // COMPARING THE CHARACTERS OF ALL OTHER STRING WITH THE SMALLEST STRING AND...\n String check=strs[index];\n <!-- System.out.println(check); -->\n for(int i=0;i<check.length();i++)\n {\n char ch=check.charAt(i);\n for(int j=0;j<strs.length;j++)\n {\n if(strs[j].charAt(i)!=ch)\n {\n return ans+"";\n }\n \n }\n ans.append(ch);\n }\n return ans+"";\n }\n}\n```
1,343
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
2,016
8
\n# Code\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& strs) {\n string ans="";\n vector<int>len; //To store the length of every string present in the vector;\n int row=strs.size(); //size of row;\n for(int i=0;i<rows;i++)\n {\n len.emplace_back(strs[i].length()); \n }\n sort(len.begin(),len.end()); //Sort the len vector to find the minimum size;\n int col=len[0]; //Store the minimum size in column ;\n bool flag=true;\n for(int i=0;i<col;i++)\n { //column wise traversal\n for(int j=1;j<row;j++)\n {\n //Check every element in the column if it is equal to its next element or not\n \n if(strs[j-1][i]!=strs[j][i]){ \n //If elements are not equal then make flag = false and break the loop \n flag=false;\n break;\n }\n }\n if(flag==true) \n count++; //This will store the numbers of column which are equal\n }\n\n ans=strs[0].substr(0,count); //take the substring(of size equal to count) from any string present in strs vector;\n return ans;\n\n }\n};\n```
1,347
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
9,450
47
```\nclass Solution:\n def longestCommonPrefix(self, strs):\n\n if not strs:\n return ""\n shortest = min(strs,key=len)\n for i, ch in enumerate(shortest):\n for other in strs:\n if other[i] != ch:\n return shortest[:i]\n return shortest \n```
1,349
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
19,546
35
# Intuition:\nThe idea behind this solution is to start with the first string in the vector `strs` and consider it as the initial common prefix. Then, iterate through the remaining strings and continuously update the common prefix by removing characters from the end until the common prefix is found in the current string at the beginning. If the common prefix becomes empty at any point, it means there is no common prefix among the strings, so we return an empty string.\n\n# Approach:\n1. Check if the vector `strs` is empty. If it is, there are no strings to compare, so we return an empty string.\n2. Initialize a string variable `ans` with the first string in `strs`. This will be our initial common prefix.\n3. Iterate through the remaining strings starting from the second string.\n4. Inside the loop, use a while loop to check if the current string does not start with the current `ans`.\n5. If the current string does not start with `ans`, remove the last character from `ans` by using the `substr` function and updating it to `ans.substr(0, ans.length() - 1)`.\n6. Check if `ans` becomes empty after removing the character. If it does, it means there is no common prefix among the strings, so we return an empty string.\n7. Repeat steps 4-6 until the current string starts with `ans`.\n8. After the loop ends, the value of `ans` will be the longest common prefix among all the strings. Return `ans`.\n\n# Complexity:\n- Time complexity: O(n), where n is the total number of characters in all the strings combined. This is because we iterate through each character of the strings to find the common prefix.\n- Space complexity: O(1) because we are using a constant amount of space to store the common prefix (`ans`) and the loop variables.\n\n---\n# C++\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& strs) {\n if(strs.size()==0){\n return "";\n }\n string ans=strs[0];\n for(int i=1;i<strs.size();i++){\n while(strs[i].find(ans) != 0 ){\n cout<< ans.substr(0,ans.length() -1)<<endl;\n ans = ans.substr(0,ans.length() -1);\n if(ans.empty()){\n return "";\n }\n } \n }\n return ans;\n }\n};\n```\n\n---\n# JAVA\n```\nclass Solution {\n public String longestCommonPrefix(String[] strs) {\n if (strs.length == 0) {\n return "";\n }\n String ans = strs[0];\n for (int i = 1; i < strs.length; i++) {\n while (strs[i].indexOf(ans) != 0) {\n ans = ans.substring(0, ans.length() - 1);\n if (ans.isEmpty()) {\n return "";\n }\n }\n }\n return ans;\n }\n}\n\n```\n\n---\n\n# Python\n```\nclass Solution(object):\n def longestCommonPrefix(self, strs):\n if len(strs) == 0:\n return \'\'\n ans = strs[0]\n for i in range(1, len(strs)):\n while ans != strs[i][:len(ans)]:\n ans = ans[:-1]\n if ans == \'\':\n return \'\'\n return ans\n\n```\n\n---\n# JavaScript\n```\nvar longestCommonPrefix = function(strs) {\n if (strs.length === 0) {\n return \'\';\n }\n let ans = strs[0];\n for (let i = 1; i < strs.length; i++) {\n while (strs[i].indexOf(ans) !== 0) {\n ans = ans.substring(0, ans.length - 1);\n if (ans === \'\') {\n return \'\';\n }\n }\n }\n return ans;\n};\n```
1,355
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
16,639
150
```\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n \n pre = strs[0]\n \n for i in strs:\n while not i.startswith(pre):\n pre = pre[:-1]\n \n return pre \n```
1,356
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
2,804
16
Simple & fast.\n```\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n if len(strs) == 0: return ""\n \n longPref = strs[0]\n \n for string in strs:\n for index in range(0, len(longPref)):\n if (index >= len(string) or longPref[index] != string[index]):\n longPref = longPref[0:index]\n break\n \n return longPref\n```
1,364
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
2,374
13
# Intuition\n# Approach\n1.short the string \n sort(str.begin(), str.end())\n it will short in alphabetically order\n such that no need to compair string in between start and last string so\n \n2.compair first string alphabet with last string alphabet\n3.store in another string if alphabet gets equall;\n\n \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& str) {\n string ans=""; //to store result \n sort(str.begin(), str.end()); \n string firstStr=str[0];\n string lastStr=str[str.size()-1]; \n for(int i=0; i<firstStr.size(); i++)\n {\n if(firstStr[i]==lastStr[i])//compair first string alphabet with last string alphabet\n {\n ans=ans+firstStr[i];\n }\n else \n break;\n }\n return ans;\n }\n};\n```
1,366
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
1,549
11
# Approach\n<!-- Describe your approach to solving the problem. -->\nWhen you sort an array, it is enough to check for the common characters of the the first & last string of the sorted vector.\n\n# Code\n```\nclass Solution {\npublic:\n string longestCommonPrefix(vector<string>& str) \n {\n sort(str.begin(), str.end()); //sorting the array\n string ans=""; //creating a new empty string to store the common prefixes\n for(int i=0;i<str[0].length();i++) // max iterations = length of the first string\n {\n if(str[0][i]!=str[str.size()-1][i]) // checking the characters of the first and last string\n break;\n ans+=str[0][i]; // concatinate if the characters are matching\n }\n return ans;\n }\n};\n```
1,368
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
499
10
# 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 String longestCommonPrefix(String[] strs) {\n if (strs.length == 0){\n return "";\n }\n\n String prefix = strs[0];\n int length = prefix.length();\n\n for (int i = 1; i < strs.length; i++) {\n while (strs[i].indexOf(prefix) != 0){\n prefix = prefix.substring(0 , --length);\n if (length == 0){\n return "";\n }\n }\n \n }\n\n return prefix;\n }\n}\n```\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository]()\n\n\n![b0e5afaa-48ec-4dcc-bd96-e39aa7a524f8_1681948924.2890832.png]()\n
1,370
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
32,636
255
**using enumerater** ``` class Solution: def longestCommonPrefix(self, m): if not m: return '' #since list of string will be sorted and retrieved min max by alphebetic order s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] #stop until hit the split index return s1 ```
1,373
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
3,048
5
```\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n res = ""\n for i in range(len(strs[0])):\n for s in strs:\n # print("this is s[i] ",s[i])\n # print("this is strs[0][i] ",strs[0][i])\n if i == len(s) or s[i] != strs[0][i]:\n return res\n # print("here we add it to res")\n res += strs[0][i]\n return res\n```
1,374
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
22,999
215
* list(zip(*strs))\nstrs = ["flower","flow","flight"]\n```\nstrs = ["flower","flow","flight"]\nl = list(zip(*strs))\n>>> l = [(\'f\', \'f\', \'f\'), (\'l\', \'l\', \'l\'), (\'o\', \'o\', \'i\'), (\'w\', \'w\', \'g\')]\n```\n```\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n l = list(zip(*strs))\n prefix = ""\n for i in l:\n if len(set(i))==1:\n prefix += i[0]\n else:\n break\n return prefix\n```\n* traditional scan vertically\n```\n i 0 1 2 3 4 5\n 0 f l o w e r\n 1\t f l o w\n 2\t f l i g h t\n\t\t\nWe choose the first string in the list as a reference. in this case is str[0] = "flower"\nthe outside for-loop go through each character of the str[0] or "flower". f->l->o->w->e->r\nthe inside for-loop, go through the words, in this case is flow, flight.\n\n\nstrs[j][i] means the the i\'s character of the j words in the strs.\n\nthere are 3 cases when we proceed the scan:\n\ncase 1: strs[j][i] = c, strs[1][2] = \'o\' and strs[0][2] = \'o\'; keep going;\ncase 2: strs[j][i] != c, strs[2][2] = \'i\' and strs[0][2] = \'o\'; break the rule, we can return strs[j][:i]. when comes to slicing a string, [:i] won\'t include the index i;\ncase 3: i = len(strs[j]) which means current word at strs[j] doesn\'t have character at index i, since it\'s 0 based index. the lenght equals i, the index ends at i - 1; break the rule, we can return.\n\n \n```\n\n\n```\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n if strs == None or len(strs) == 0: return ""\n for i in range(len(strs[0])): \n c = strs[0][i]// \n for j in range(1,len(strs)):\n if i == len(strs[j]) or strs[j][i] != c:\n return strs[0][:i]\n return strs[0] if strs else ""\n```
1,380
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
3,300
11
**Which have included C#, Java, Python3,JavaScript solutions**\n**\u2B50[]()\u2B50**\n\n\n#### Example : Java Code \u27A1 Runtime : 1ms\n```\nclass Solution {\n public String longestCommonPrefix(String[] strs) {\n for (int i = 0; i < strs[0].length(); i++) \n {\n char tmpChar = strs[0].charAt(i); \n for (int j = 0; j < strs.length; j++) \n {\n if (strs[j].length() == i || strs[j].charAt(i) != tmpChar) \n {\n return strs[0].substring(0, i);\n }\n }\n }\n return strs[0]; \n }\n}\n```\n**You can find a faster Java solution in the link.**\n\n\nIf you got any problem about the explanation or you need other programming language solution, please feel free to leave your comment.\n\n**\uD83E\uDDE1See more LeetCode solution : [Zyrastory - LeetCode Solution]()**
1,382
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
3,040
10
![image]()\n\n```\nclass Solution {\n public String longestCommonPrefix(String[] strs) {\n String r="";\n int n=strs.length;\n Arrays.sort(strs);//Sorted first\n String s=strs[0];//smallest no of char\n String h=strs[n-1];//highest no of char\n for(int i =0;i<s.length();i++)//taken smallest length so that run time will be less\n {\n if(s.charAt(i)!=h.charAt(i)) break;\n r=r+s.charAt(i); \n }\n return r; \n }\n}\n\n//Time complexity would be O(n)\n```\n
1,384
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
171,637
368
\n public String longestCommonPrefix(String[] strs) {\n if(strs == null || strs.length == 0) return "";\n String pre = strs[0];\n int i = 1;\n while(i < strs.length){\n while(strs[i].indexOf(pre) != 0)\n pre = pre.substring(0,pre.length()-1);\n i++;\n }\n return pre;\n }
1,385
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
8,745
23
# Intuition\n**EDIT** - Earlier I used sorting, which took O(M * NLOGN) complexity.Instead we can use min() and max() , which takes O(N*M) time.complexity. (N is no.of elements in the array and M is size of the string)\n\nIf you sort the given array (lexicographically), the **first** and **last** word will be the least similar (i.e, they vary the most)\n- It is enough if you find the common prefix between the **first** and **last** word ( need not consider other words in the array )\n\n**Example:** arr = ["aad","aaf", "aaaa", "af"]\n1) Sorted arr is ["aaaa", "aad", "aaf", "af"]\n2) *first* = "aaaa", *last* = "af"\n3) Common prefix of *first* and *last* is ans = "a"\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) **Sort** the given array\n2) Take the **first** and **last** word of the array\n3) Find the common **prefix** of the first and last word\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N*M) - since use min() and max() in python, where N is no.of elements in the array and M is size of the string\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) - no extra space is used\n\n# Code\n```\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n first, last = min(strs), max(strs)\n prefix = \'\'\n for ind in range(min(len(first), len(last))):\n if first[ind] != last[ind]:\n break\n prefix += first[ind]\n\n return prefix\n```
1,386
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
3,403
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Firstly I was very confused about the problem because I have ignored the word "prefix". Prefix means the starting letters of the word. \n- So if the starting letter of any word in the array will not be matched then we will simply return empty string and if first word will be matched in the every array of strings using every method then we will look for the second word ans so on..\n\n# Code\n```\n/**\n * @param {string[]} strs\n * @return {string}\n */\nvar longestCommonPrefix = function (strs) {\n let output = "";\n for (let i = 0; i < strs[0].length; i++) {\n if(strs.every(str => str[i] === strs[0][i])) output += strs[0][i];\n else break;\n }\n return output;\n};\n```
1,387
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
2,352
5
# Intuition\nWe can use the first index of the array and then compare it with the others to see if they contains it or not \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nfirst we took a string prefix and stored the first index in it ;\nthen we looped through the array strs and used `.indexOf()` to check weather the next element in strs contains the prefix as a prefix or not\nIf not then we keep removing the last element until we have `String prefix` as the prefix and then continued it further ;\nAt last the String prefix will have the common prefix of all the elements outside the for loop; \n<!-- Describe your approach to solving the problem. -->\n\n\n\n# Code\n```\nclass Solution {\n public String longestCommonPrefix(String[] strs) {\n //If array does\'t contains any strings then we retuen empty string;\n if(strs.length == 0){\n return "";\n }\n //we take the first index to be the prefix string ;\n String prefix = strs[0];\n //then we used or loop for iterating \n //and changing prefix as we go further in the string ;\n for(int i = 1 ; i < strs.length ; i++){\n String str = strs[i];\n while(str.indexOf(prefix) != 0){\n prefix = prefix.substring(0,prefix.length()-1);\n }\n }\n return prefix ;\n }\n}\n```
1,388
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
943
13
# Intuition\nMy initial thoughts on solving this problem involve finding the longest common prefix among a given array of strings. I plan to sort the array first to bring the strings with the common prefix closer to each other. Then, I will compare the first and last strings in the sorted array to find the common prefix.\n\n# Approach\nI will sort the array of strings to ensure that the strings with the longest common prefix are close to each other. After sorting, I will take the first and last strings and compare their characters one by one until I encounter a mismatch. I will keep track of the count of matching characters to determine the length of the common prefix.\n\n# Complexity\n- Time complexity: O(n * m)\nHere, \'n\' is the number of strings in the array and \'m\' is the average length of the strings. Sorting the array takes O(n * log n) time, and then comparing the characters in the common prefix takes O(m) time. Thus, the overall time complexity is O(n * log n + m), which can be approximated as O(n * m).\n\n- Space complexity: O(1)\n The algorithm uses a constant amount of extra space for variables.\n\n# Code\n```\nclass Solution {\n public String longestCommonPrefix(String[] strs) {\n\n int count = 0;\n\n Arrays.sort(strs);\n\n String start = strs[0];\n\n String end = strs[strs.length-1];\n\n int i = 0 ;\n while (i<start.length() && i<end.length()){\n\n if(start.charAt(i) == end.charAt(i)){\n\n count++;\n i++;\n }\n else {\n break;\n }\n\n\n }\n\n return start.substring(0,count);\n \n\n }\n}\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]()
1,393
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
String
Easy
null
1,553
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using string.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the approach by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity : O(N*L), The time complexity of the above code i (N*L). For every length in range [0, L], we\u2019re checking whether all the strings have the common prefix, where N = the total number of strings and L is the minimum length of the string.\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity : O(1), The space complexity of the above code is O(1) since we\u2019re using the constant space.\n\n# Code\n```\n/*\n\n Time Complexity : O(N*L), The time complexity of the above code is O(N*L). For every length in range [0, L],\n we\u2019re checking whether all the strings have the common prefix, where N = the total number of strings and L is\n the minimum length of the string.\n\n Space Complexity : O(1), The space complexity of the above code is O(1) since we\u2019re using the constant space.\n\n Solved using String.\n\n*/\n\nclass Solution { \npublic:\n string longestCommonPrefix(vector<string>& strs) {\n int lcpLength = 0;\n for(int i=0; i<strs[0].length(); i++){\n bool flag = true;\n for(auto s : strs){\n if(lcpLength >= s.length() || s[lcpLength] != strs[0][lcpLength]){\n flag = false;\n break;\n }\n }\n if(flag == true){\n lcpLength++;\n }\n else{\n break;\n }\n }\n return strs[0].substr(0,lcpLength);\n }\n};\n\n```\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]()
1,396
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
162,242
608
# Intuition of this Problem:\nSet is used to prevent duplicate triplets and parallely we will use two pointer approach to maintain J and k.\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Sort the input array\n2. Initialize a set to store the unique triplets and an output vector to store the final result\n3. Iterate through the array with a variable i, starting from index 0.\n4. Initialize two pointers, j and k, with j starting at i+1 and k starting at the end of the array.\n5. In the while loop, check if the sum of nums[i], nums[j], and nums[k] is equal to 0. If it is, insert the triplet into the set and increment j and decrement k to move the pointers.\n6. If the sum is less than 0, increment j. If the sum is greater than 0, decrement k.\n7. After the while loop, iterate through the set and add each triplet to the output vector.\n8. Return the output vector\n<!-- Describe your approach to solving the problem. -->\n\n# Code:\n```C++ []\n//Optimized Approach - O(n^2 logn + nlogn) - o(n^2 logn) time and O(n) space\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int target = 0;\n sort(nums.begin(), nums.end());\n set<vector<int>> s;\n vector<vector<int>> output;\n for (int i = 0; i < nums.size(); i++){\n int j = i + 1;\n int k = nums.size() - 1;\n while (j < k) {\n int sum = nums[i] + nums[j] + nums[k];\n if (sum == target) {\n s.insert({nums[i], nums[j], nums[k]});\n j++;\n k--;\n } else if (sum < target) {\n j++;\n } else {\n k--;\n }\n }\n }\n for(auto triplets : s)\n output.push_back(triplets);\n return output;\n }\n};\n```\n```C++ []\n//Bruteforce Approach - O(n^3) time and O(n) space\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n set<vector<int>> s;\n vector<vector<int>> output;\n for (int i = 0; i < nums.size(); i++){\n for(int j = i+1; j < nums.size(); j++){\n for(int k = j+1; k < nums.size(); k++){\n vector<int> temp;\n if(nums[i] + nums[j] + nums[k] == 0){\n temp.push_back(nums[i]);\n temp.push_back(nums[j]);\n temp.push_back(nums[k]);\n s.insert(temp);\n }\n }\n }\n }\n for(auto allTriplets : s)\n output.push_back(allTriplets);\n return output;\n }\n};\n```\n```Java []\nclass Solution {\n public List<List<Integer>> threeSum(int[] nums) {\n int target = 0;\n Arrays.sort(nums);\n Set<List<Integer>> s = new HashSet<>();\n List<List<Integer>> output = new ArrayList<>();\n for (int i = 0; i < nums.length; i++){\n int j = i + 1;\n int k = nums.length - 1;\n while (j < k) {\n int sum = nums[i] + nums[j] + nums[k];\n if (sum == target) {\n s.add(Arrays.asList(nums[i], nums[j], nums[k]));\n j++;\n k--;\n } else if (sum < target) {\n j++;\n } else {\n k--;\n }\n }\n }\n output.addAll(s);\n return output;\n }\n}\n\n```\n```Python []\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n target = 0\n nums.sort()\n s = set()\n output = []\n for i in range(len(nums)):\n j = i + 1\n k = len(nums) - 1\n while j < k:\n sum = nums[i] + nums[j] + nums[k]\n if sum == target:\n s.add((nums[i], nums[j], nums[k]))\n j += 1\n k -= 1\n elif sum < target:\n j += 1\n else:\n k -= 1\n output = list(s)\n return output\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(n^2 logn)** // where n is the size of array\nSorting takes O(nlogn) time and loop takes O(n^2) time, So the overall time complexity is O(nlogn + n^2 logn) - O(n^2 logn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)** // for taking hashset.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1,401
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
37,853
264
# 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)$$ -->O(N)^2\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(N)\n\n![Screenshot_20230205_171246.png]()\n\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> threeSum(int[] nums) {\n List<List<Integer>> ans = new ArrayList<>();\n\n // Sort the array\n Arrays.sort(nums);\n\n for (int i = 0; i < nums.length - 2; i++) {\n // Skip duplicate elements for i\n if (i > 0 && nums[i] == nums[i - 1]) {\n continue;\n }\n\n int j = i + 1;\n int k = nums.length - 1;\n\n while (j < k) {\n int sum = nums[i] + nums[j] + nums[k];\n\n if (sum == 0) {\n // Found a triplet with zero sum\n ans.add(Arrays.asList(nums[i], nums[j], nums[k]));\n\n // Skip duplicate elements for j\n while (j < k && nums[j] == nums[j + 1]) {\n j++;\n }\n\n // Skip duplicate elements for k\n while (j < k && nums[k] == nums[k - 1]) {\n k--;\n }\n\n // Move the pointers\n j++;\n k--;\n } else if (sum < 0) {\n // Sum is less than zero, increment j to increase the sum\n j++;\n } else {\n // Sum is greater than zero, decrement k to decrease the sum\n k--;\n }\n }\n }\n return ans;\n }\n}\n\n```
1,402
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
4,204
16
\u270598.21%\uD83D\uDD25HashMap & Two Pointer \uD83D\uDD25 \uD83D\uDD25\n\n# Read article and Contain Codes c++, java , Python ,Javascript : \n\n\n1) Two Pointer\n[Cpp]()\n[Java]()\n[JavaScript]()\n[Python]()\n\n2) Hashmap\n[Cpp]()\n[Java]()\n[JavaScript]()\n[Python]()\n\n\nFirst, we can create a HashMap to store the frequency of each number in the array. Then, we can iterate through the array and for each element, we can check if there exists two other numbers in the array that add up to the target sum minus the current element. We can do this by using two pointers - one starting from the next index of the current element and another starting from the last index of the array.\n\nBy incrementing or decrementing these pointers based on whether their sum with the current element is greater or smaller than the target sum, we can find all possible triplets that satisfy the condition. We also need to make sure that we don\'t consider duplicate triplets, so we can use additional conditions to skip over duplicates.\n\nOverall, this approach has a time complexity of O(N^2): we are using one for loops to get values of a, and for every value of a, we find the pair b,c (such that a+b+c=0) using two pointer approach that takes O(N) time. so total time complexity is of the order of O(N^2).. However, by using HashMaps and Two Pointers, we can efficiently solve the three sum problem and find all unique triplets that add up to a given target sum.\n![image]()\n
1,403
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
52,568
370
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this question using Multiple Approaches. (Here I have explained all the possible solutions of this problem).\n\n1. Solved using Array(Three Nested Loop) + Sorting + Hash Table(set). Brute Force Approach.\n2. Solved using Array(Two Nested Loop) + Sorting + Hash Table(set).\n3. Solved using Array(Two Nested Loop) + Sorting. Optimized Approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the All the approaches by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is given in code comment.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity is given in code comment.\n\n# Code\n```\n/*\n\n Time Complexity : O(N^3), Here three nested loop creates the time complexity. Where N is the size of the\n array(nums).\n\n Space Complexity : O(N), Hash Table(set) space.\n\n Solved using Array(Three Nested Loop) + Sorting + Hash Table(set). Brute Force Approach.\n\n Note : this will give TLE.\n\n*/\n\n\n/***************************************** Approach 1 *****************************************/\n\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n set<vector<int>> set;\n vector<vector<int>> output;\n for(int i=0; i<n-2; i++){\n for(int j=i+1; j<n-1; j++){\n for(int k=j+1; k<n; k++){\n if((nums[i] + nums[j] + nums[k] == 0) && i != j && j != k && k != i){\n set.insert({nums[i], nums[j], nums[k]});\n }\n }\n }\n }\n for(auto it : set){\n output.push_back(it);\n }\n return output;\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(N^2), Here Two nested loop creates the time complexity. Where N is the size of the\n array(nums).\n\n Space Complexity : O(N), Hash Table(set) space.\n\n Solved using Array(Two Nested Loop) + Sorting + Hash Table(set).\n\n*/\n\n\n/***************************************** Approach 2 *****************************************/\n\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n set<vector<int>> set;\n vector<vector<int>> output;\n for(int i=0; i<n-2; i++){\n int low = i+1, high = n-1;\n while(low < high){\n if(nums[i] + nums[low] + nums[high] < 0){\n low++;\n }\n else if(nums[i] + nums[low] + nums[high] > 0){\n high--;\n }\n else{\n set.insert({nums[i], nums[low], nums[high]});\n low++;\n high--;\n }\n }\n }\n for(auto it : set){\n output.push_back(it);\n }\n return output;\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(N^2), Here Two nested loop creates the time complexity. Where N is the size of the\n array(nums).\n\n Space Complexity : O(1), Constant space. Extra space is only allocated for the Vector(output), however the\n output does not count towards the space complexity.\n\n Solved using Array(Two Nested Loop) + Sorting. Optimized Approach.\n\n*/\n\n\n/***************************************** Approach 3 *****************************************/\n\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n vector<vector<int>> output;\n for(int i=0; i<n-1; i++){\n int low = i+1, high = n-1;\n while(low < high){\n if(nums[i] + nums[low] + nums[high] < 0){\n low++;\n }\n else if(nums[i] + nums[low] + nums[high] > 0){\n high--;\n }\n else{\n output.push_back({nums[i], nums[low], nums[high]});\n int tempIndex1 = low, tempIndex2 = high;\n while(low < high && nums[low] == nums[tempIndex1]) low++;\n while(low < high && nums[high] == nums[tempIndex2]) high--;\n }\n }\n while(i+1 < n && nums[i] == nums[i+1]) i++;\n }\n return output;\n }\n};\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]()
1,404
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
106,403
921
Requirements we need to fulfil: Find the triplets having sum = 0.\n\nAs array has both -ve and +ve numbers, firstly we sort the array. Sorted array would have -ve numbers together and +ve numbers together in an increasing order. This will make easy for searching the required numbers to make a 0 sum.\n\nBase cases after sorting:\n- If array size is < 3, means no triplet would exist from that array. Return empty vector of vectors.\n- If first element is +ve, that means there is no -ve number by which we can make a 0 triplet sum. Return empty vector of vectors.\n\n### Two Pointer Approach:\n\nThe basic thinking logic for this is: Fix any one number in sorted array and find the other two numbers after it. The other two numbers can be easily found using two pointers (as array is sorted) and two numbers should have sum = -1*(fixed number).\n\n- Traverse the array and fix a number at every iteration.\n- If number fixed is +ve, break there because we can\'t make it zero by searching after it.\n- If number is getting repeated, ignore the lower loop and continue. This is for unique triplets. We want the last instance of the fixed number, if it is repeated.\n- Make two pointers high and low, and initialize sum as 0.\n- Search between two pointers, just similiar to binary search. Sum = num[i] + num[low] + num[high].\n- If sum is -ve, means, we need more +ve numbers to make it 0, increament low (low++).\n- If sum is +ve, means, we need more -ve numbers to make it 0, decreament high (high--).\n- If sum is 0, that means we have found the required triplet, push it in answer vector.\n- Now again, to avoid duplicate triplets, we have to navigate to last occurences of num[low] and num[high] respectively. Update the low and high with last occurences of low and high.\n\nMy Two Pointer Submission:\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n sort(nums.begin() , nums.end()); //Sorted Array\n if(nums.size() < 3){ //Base case 1\n return {};\n }\n if(nums[0] > 0){ //Base case 2\n return {};\n }\n vector<vector<int>> answer;\n for(int i = 0 ; i < nums.size() ; ++i){ //Traversing the array to fix the number.\n if(nums[i] > 0){ //If number fixed is +ve, stop there because we can\'t make it zero by searching after it.\n break;\n }\n if(i > 0 && nums[i] == nums[i - 1]){ //If number is getting repeated, ignore the lower loop and continue.\n continue;\n }\n int low = i + 1 , high = nums.size() - 1; //Make two pointers high and low, and initialize sum as 0.\n int sum = 0;\n while(low < high){ //Search between two pointers, just similiar to binary search.\n sum = nums[i] + nums[low] + nums[high];\n if(sum > 0){ //If sum is +ve, means, we need more -ve numbers to make it 0, decreament high (high--).\n high--;\n } else if(sum < 0){ //If sum is -ve, means, we need more +ve numbers to make it 0, increament low (low++).\n low++;\n } else {\n answer.push_back({nums[i] , nums[low] , nums[high]}); //we have found the required triplet, push it in answer vector\n int last_low_occurence = nums[low] , last_high_occurence = nums[high]; //Now again, to avoid duplicate triplets, we have to navigate to last occurences of num[low] and num[high] respectively\n while(low < high && nums[low] == last_low_occurence){ // Update the low and high with last occurences of low and high.\n low++;\n }\n while(low < high && nums[high] == last_high_occurence){\n high--;\n }\n }\n }\n }\n return answer; //Return the answer vector.\n }\n};\n```\n\n### HashMap Approach:\n\nIn this approach, firstly, we will hash the indices of all elements in a hashMap. In case of repeated elements, the last occurence index would be stored in hashMap. \n\n- Here also we fix a number (num[i]), by traversing the loop. But the loop traversal here for fixing numbers would leave last two indices. These last two indices would be covered by the nested loop. \n- If number fixed is +ve, break there because we can\'t make it zero by searching after it.\n- Make a nested loop to fix a number after the first fixed number. (num[j])\n- To make sum 0, we would require the -ve sum of both fixed numbers. Let us say this required.\n- Now, we will find the this required number in hashMap. If it exists in hashmap and its last occurrence index > 2nd fixed index, we found our triplet. Push it in answer vector.\n- Update j to last occurence of 2nd fixed number to avoid duplicate triplets.\n- Update i to last occurence of 1st fixed number to avoid duplicate triplets.\n- Return answer vector.\n\nMy HashMap Submission:\n\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n sort(nums.begin() , nums.end()); //Sorted Array\n if(nums.size() < 3){ // Base Case 1\n return {};\n }\n if(nums[0] > 0){ // Base Case 2\n return {};\n }\n unordered_map<int , int> hashMap;\n for(int i = 0 ; i < nums.size() ; ++i){ //Hashing of Indices\n hashMap[nums[i]] = i;\n }\n vector<vector<int>> answer;\n for(int i = 0 ; i < nums.size() - 2 ; ++i){ //Traversing the array to fix the number.\n if(nums[i] > 0){ //If number fixed is +ve, stop there because we can\'t make it zero by searching after it.\n break;\n }\n for(int j = i + 1 ; j < nums.size() - 1 ; ++j){ //Fixing another number after first number\n int required = -1*(nums[i] + nums[j]); //To make sum 0, we would require the -ve sum of both fixed numbers.\n if(hashMap.count(required) && hashMap.find(required)->second > j){ //If it exists in hashmap and its last occurrence index > 2nd fixed index, we found our triplet.\n answer.push_back({nums[i] , nums[j] , required});\n }\n j = hashMap.find(nums[j])->second; //Update j to last occurence of 2nd fixed number to avoid duplicate triplets.\n }\n i = hashMap.find(nums[i])->second; //Update i to last occurence of 1st fixed number to avoid duplicate triplets.\n }\n return answer; //Return answer vector.\n }\n};\n```\n\n**PLEASE UPVOTE IT IF YOU LIKED IT, IT REALLY MOTIVATES :)**
1,405
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
136,316
888
```python\ndef threeSum(self, nums: List[int]) -> List[List[int]]:\n\n\tres = set()\n\n\t#1. Split nums into three lists: negative numbers, positive numbers, and zeros\n\tn, p, z = [], [], []\n\tfor num in nums:\n\t\tif num > 0:\n\t\t\tp.append(num)\n\t\telif num < 0: \n\t\t\tn.append(num)\n\t\telse:\n\t\t\tz.append(num)\n\n\t#2. Create a separate set for negatives and positives for O(1) look-up times\n\tN, P = set(n), set(p)\n\n\t#3. If there is at least 1 zero in the list, add all cases where -num exists in N and num exists in P\n\t# i.e. (-3, 0, 3) = 0\n\tif z:\n\t\tfor num in P:\n\t\t\tif -1*num in N:\n\t\t\t\tres.add((-1*num, 0, num))\n\n\t#3. If there are at least 3 zeros in the list then also include (0, 0, 0) = 0\n\tif len(z) >= 3:\n\t\tres.add((0,0,0))\n\n\t#4. For all pairs of negative numbers (-3, -1), check to see if their complement (4)\n\t# exists in the positive number set\n\tfor i in range(len(n)):\n\t\tfor j in range(i+1,len(n)):\n\t\t\ttarget = -1*(n[i]+n[j])\n\t\t\tif target in P:\n\t\t\t\tres.add(tuple(sorted([n[i],n[j],target])))\n\n\t#5. For all pairs of positive numbers (1, 1), check to see if their complement (-2)\n\t# exists in the negative number set\n\tfor i in range(len(p)):\n\t\tfor j in range(i+1,len(p)):\n\t\t\ttarget = -1*(p[i]+p[j])\n\t\t\tif target in N:\n\t\t\t\tres.add(tuple(sorted([p[i],p[j],target])))\n\n\treturn res\n```\n<img src = "" width = "500px">
1,410
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
34,884
114
# Intuition\n*3 solutions, Each latter is more optimized!*\n\n# Complexity\n- Time complexity:\nO(n^2)\n ***Note, these are worst case complexity, optimization improves the runtime.***\n\n- Space complexity:\nO(n)\n ***Note, This is the dominant or the higher order space complexity, while optimizing the space incurred might be higher but it will always be linear to the input size..***\n\n\n# Approach - 1\nThe 3-sum problem using the two-pointer approach. Here\'s a breakdown of how it works:\n\n1. The function `threeSum` takes an input list of integers called `nums` and returns a list of lists, representing the triplets that satisfy the 3-sum condition.\n\n2. The first step is to sort the input array `nums` in ascending order using the `sort()` method. Sorting the array is necessary to apply the two-pointer approach efficiently.\n\n3. A set called `triplets` is initialized to store the unique triplets that satisfy the 3-sum condition. Using a set helps avoid duplicate entries in the final result.\n\n4. The code then proceeds with a loop that iterates through each element of the array, up to the second-to-last element (`len(nums) - 2`). This is because we need at least three elements to form a triplet.\n\n5. Within the loop, the current element at index `i` is assigned to the variable `firstNum`. Two pointers, `j` and `k`, are initialized. `j` starts from `i + 1` (the element next to `firstNum`), and `k` starts from the last element of the array.\n\n6. A while loop is used to find the pairs (`secondNum` and `thirdNum`) that can form a triplet with `firstNum`. The loop continues as long as `j` is less than `k`.\n\n7. Inside the while loop, the current values at indices `j` and `k` are assigned to `secondNum` and `thirdNum`, respectively.\n\n8. The `potentialSum` variable stores the sum of `firstNum`, `secondNum`, and `thirdNum`.\n\n9. If `potentialSum` is greater than 0, it means the sum is too large. In this case, we decrement `k` to consider a smaller value.\n\n10. If `potentialSum` is less than 0, it means the sum is too small. In this case, we increment `j` to consider a larger value.\n\n11. If `potentialSum` is equal to 0, it means we have found a triplet that satisfies the 3-sum condition. The triplet `(firstNum, secondNum, thirdNum)` is added to the `triplets` set. Additionally, both `j` and `k` are incremented and decremented, respectively, to explore other possible combinations.\n\n12. After the loop ends, the function returns the `triplets` set, which contains all the unique triplets that sum to zero.\n\n# Code : Beats 23.46% *(Easy to understand)*\n```\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n nums.sort()\n triplets = set()\n for i in range(len(nums) - 2):\n firstNum = nums[i]\n j = i + 1\n k = len(nums) - 1\n while j < k:\n secondNum = nums[j]\n thirdNum = nums[k]\n\n potentialSum = firstNum + secondNum + thirdNum \n if potentialSum > 0:\n k -= 1\n elif potentialSum < 0:\n j += 1\n else:\n triplets.add((firstNum , secondNum ,thirdNum))\n j += 1\n k -= 1\n return triplets\n```\n\n# Approach - 2\nThis is an *`enhanced version`* of the previous solution. It includes additional checks to skip duplicate values and improve efficiency. Here\'s an explanation of the changes and the updated time and space complexity:\n\nChanges in the Code:\n1. Right after sorting the array, the code includes an `if` statement to check for duplicate values of the first number. If `nums[i]` is the same as `nums[i - 1]`, it means we have already processed a triplet with the same first number, so we skip the current iteration using the `continue` statement.\n\n2. Inside the `else` block where a triplet is found, the code includes two additional `while` loops to skip duplicate values of the second and third numbers. These loops increment `j` and decrement `k` until the next distinct values are encountered.\n\n\nOverall, the time complexity is improved due to skipping duplicate values, resulting in a more efficient execution. The time complexity remains O(n^2) in the worst case but with better average-case performance.\n\n\n# Code: Optimized, Beats: 57.64%\n```\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n nums.sort()\n triplets = set()\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]:\n continue # Skip duplicate values of the first number\n firstNum = nums[i]\n j, k = i + 1, len(nums) - 1\n while j < k:\n secondNum, thirdNum = nums[j], nums[k]\n potentialSum = firstNum + secondNum + thirdNum \n if potentialSum > 0:\n k -= 1\n elif potentialSum < 0:\n j += 1\n else:\n triplets.add((firstNum, secondNum, thirdNum))\n j, k = j + 1, k - 1\n while j < k and nums[j] == nums[j - 1]:\n j += 1 # Skip duplicate values of the second number\n while j < k and nums[k] == nums[k + 1]:\n k -= 1 # Skip duplicate values of the third number\n return triplets\n```\n\n# Approach - 3\n\nThis code is another implementation of the Three Sum problem that uses `defaultdict` from the `collections` module. Here\'s an explanation of the code:\n\n1. The code initializes three variables: `negative`, `positive`, and `zeros` as defaultdicts with a default value of 0. These dictionaries will store the count of negative numbers, positive numbers, and zeros, respectively.\n\n2. The `for` loop iterates through each number in the input `nums` list and increments the count of the corresponding dictionary based on whether the number is negative, positive, or zero.\n\n3. The code initializes an empty list called `result`, which will store the triplets that add up to zero.\n\n4. If there are one or more zeros in the input list, the code loops through the negative numbers and checks if the complement of the negative number exists in the positive numbers dictionary. If it does, the code appends a triplet of (0, n, -n) to the `result` list.\n\n5. If there are more than two zeros in the input list, the code appends a triplet of (0,0,0) to the `result` list.\n\n6. The code loops through pairs of negative and positive dictionaries and iterates through each pair of keys `(j, k)` in the dictionary. Then, it loops through each pair of keys `(j2, k2)` in the same dictionary, starting from the current index in the outer loop to avoid duplicates. Finally, the code checks if the complement of the sum of the two keys exists in the opposite dictionary (e.g., if the current loop is on the negative dictionary, it checks if the complement exists in the positive dictionary). If it does, the code appends a triplet of `(j, j2, -j-j2)` to the `result` list.\n\n7. The `result` list is returned at the end of the function.\n\n\n# Code - Beats: 99.48\n```\nfrom collections import defaultdict\n\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n negative = defaultdict(int)\n positive = defaultdict(int)\n zeros = 0\n for num in nums:\n if num < 0:\n negative[num] += 1\n elif num > 0:\n positive[num] += 1\n else:\n zeros += 1\n \n result = []\n if zeros:\n for n in negative:\n if -n in positive:\n result.append((0, n, -n)) \n if zeros > 2:\n result.append((0,0,0))\n\n for set1, set2 in ((negative, positive), (positive, negative)):\n set1Items = list(set1.items())\n for i, (j, k) in enumerate(set1Items):\n for j2, k2 in set1Items[i:]:\n if j != j2 or (j == j2 and k > 1):\n if -j-j2 in set2:\n result.append((j, j2, -j-j2))\n return result\n```\n\n# Above Complexity: [in Depth]\n\n`Time Complexity`:\n1. The `for` loop that counts the occurrence of each number in the input list takes `O(n)` time.\n\n2. The loop that checks for zero triplets takes `O(n)` time in the worst case, as it iterates through each negative number and checks if its complement exists in the positive numbers dictionary.\n\n3. The loop that checks for non-zero triplets takes `O(n^2)` time in the worst case, as it iterates through each pair of keys in each dictionary and checks if their complement exists in the opposite dictionary.\n\n4. The overall `time complexity` of the function is `O(n^2)`, as the loop that takes the most time is the one that checks for non-zero triplets.\n\n`Space Complexity`:\n1. The space complexity is `O(n)` for the three `defaultdict` dictionaries, as they store the count of each number in the input list.\n\n2. The space complexity of the `result` list is also `O(n)` in the worst case, as there can be up to `O(n)` triplets that add up to zero\n\n\nIn summary, this implementation of the Three Sum problem also has a time complexity of `O(n^2)` and a space complexity of `O(n)`. However, it uses `defaultdict` to count the occurrence of each number in the input list and improves the efficiency of checking for zero triplets by using a dictionary lookup instead of iterating through the list.
1,411
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
253,223
1,300
the key idea is the same as the `TwoSum` problem. When we fix the `1st` number, the `2nd` and `3rd` number can be found following the same reasoning as `TwoSum`. \n\nThe only difference is that, the `TwoSum` problem of LEETCODE has a unique solution. However, in `ThreeSum`, we have multiple duplicate solutions that can be found. Most of the OLE errors happened here because you could\'ve ended up with a solution with so many duplicates.\n\nThe naive solution for the duplicates will be using the STL methods like below :\n\n\n std::sort(res.begin(), res.end());\n res.erase(unique(res.begin(), res.end()), res.end());\n\n\nBut according to my submissions, this way will cause you double your time consuming almostly.\n\nA better approach is that, to jump over the number which has been scanned, no matter it is part of some solution or not.\n\nIf the three numbers formed a solution, we can safely ignore all the duplicates of them.\n\nWe can do this to all the three numbers such that we can remove the duplicates. \n\nHere\'s my AC C++ Code:\n\n\n vector<vector<int> > threeSum(vector<int> &num) {\n \n vector<vector<int> > res;\n\n std::sort(num.begin(), num.end());\n\n for (int i = 0; i < num.size(); i++) {\n \n int target = -num[i];\n int front = i + 1;\n int back = num.size() - 1;\n\n while (front < back) {\n\n int sum = num[front] + num[back];\n \n // Finding answer which start from number num[i]\n if (sum < target)\n front++;\n\n else if (sum > target)\n back--;\n\n else {\n vector<int> triplet = {num[i], num[front], num[back]};\n res.push_back(triplet);\n \n // Processing duplicates of Number 2\n // Rolling the front pointer to the next different number forwards\n while (front < back && num[front] == triplet[1]) front++;\n\n // Processing duplicates of Number 3\n // Rolling the back pointer to the next different number backwards\n while (front < back && num[back] == triplet[2]) back--;\n }\n \n }\n\n // Processing duplicates of Number 1\n while (i + 1 < num.size() && num[i + 1] == num[i]) \n i++;\n\n }\n \n return res;\n \n }
1,416
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
71,941
719
```\n public List<List<Integer>> threeSum(int[] nums) {\n Set<List<Integer>> res = new HashSet<>();\n if(nums.length==0) return new ArrayList<>(res);\n Arrays.sort(nums);\n for(int i=0; i<nums.length-2;i++){\n int j =i+1;\n int k = nums.length-1;\n while(j<k){\n int sum = nums[i]+nums[j]+nums[k];\n if(sum==0)res.add(Arrays.asList(nums[i],nums[j++],nums[k--]));\n else if (sum >0) k--;\n else if (sum<0) j++;\n }\n\n }\n return new ArrayList<>(res);\n\n }\n```
1,418
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
632
5
1. Two Pointer Set Solution -- O(n^2) Time Complexity, O(n) Space Complexity\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n \n std::sort(nums.begin(), nums.end());\n std::unordered_set<std::vector<int>> set;\n\n for (int i = 0; i < nums.size(); i++) {\n\n int j = i+1;\n int k = nums.size()-1;\n\n while (j < k) {\n\n int sum = nums[i] + nums[j] + nums[k];\n\n if (sum == 0) {\n set.insert({nums[i], nums[j], nums[k]});\n j++;\n k--;\n }\n else if (sum > 0) {\n k--;\n }\n else if (sum < 0) {\n j++;\n } \n }\n }\n\n return std::vector<std::vector<int>> (set.begin(), set.end());\n }\n};\n```\n\n\n2. Two Pointer Without Set Solution -- O(n^2) Time Complexity, O(logn) to O(n) Space Complexity\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n \n std::sort(nums.begin(), nums.end());\n std::vector<std::vector<int>> ret;\n\n for (int i = 0; i < nums.size(); i++) {\n\n if (i > 0 && nums[i] == nums[i-1]) continue; // Handle duplicates manually\n\n int j = i+1;\n int k = nums.size()-1;\n\n while (j < k) {\n\n int sum = nums[i] + nums[j] + nums[k];\n\n if (sum == 0) {\n ret.push_back({nums[i], nums[j], nums[k]});\n j++;\n while (j < k && nums[j] == nums[j-1]) j++; // Handle duplicates manually\n }\n else if (sum > 0) {\n k--;\n }\n else if (sum < 0) {\n j++;\n } \n }\n }\n\n return ret;\n }\n};\n```
1,419
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
4,112
8
# 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 vector<vector<int>> threeSum(vector<int>& nums) {\n sort(nums.begin() , nums.end()); //Sorted Array\n if(nums.size() < 3){ //Base case 1\n return {};\n }\n if(nums[0] > 0){ //Base case 2\n return {};\n }\n vector<vector<int>> answer;\n for(int i = 0 ; i < nums.size() ; ++i){ //Traversing the array to fix the number.\n if(nums[i] > 0){ //If number fixed is +ve, stop there because we can\'t make it zero by searching after it.\n break;\n }\n if(i > 0 && nums[i] == nums[i - 1]){ //If number is getting repeated, ignore the lower loop and continue.\n continue;\n }\n int low = i + 1 , high = nums.size() - 1; //Make two pointers high and low, and initialize sum as 0.\n int sum = 0;\n while(low < high){ //Search between two pointers, just similiar to binary search.\n sum = nums[i] + nums[low] + nums[high];\n if(sum > 0){ //If sum is +ve, means, we need more -ve numbers to make it 0, decreament high (high--).\n high--;\n } else if(sum < 0){ //If sum is -ve, means, we need more +ve numbers to make it 0, increament low (low++).\n low++;\n } else {\n answer.push_back({nums[i] , nums[low] , nums[high]}); //we have found the required triplet, push it in answer vector\n int last_low_occurence = nums[low] , last_high_occurence = nums[high]; //Now again, to avoid duplicate triplets, we have to navigate to last occurences of num[low] and num[high] respectively\n while(low < high && nums[low] == last_low_occurence){ // Update the low and high with last occurences of low and high.\n low++;\n }\n while(low < high && nums[high] == last_high_occurence){\n high--;\n }\n }\n }\n }\n return answer; //Return the answer vector.\n }\n};\n```
1,422
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
267,401
861
\n def threeSum(self, nums):\n res = []\n nums.sort()\n for i in xrange(len(nums)-2):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n l, r = i+1, len(nums)-1\n while l < r:\n s = nums[i] + nums[l] + nums[r]\n if s < 0:\n l +=1 \n elif s > 0:\n r -= 1\n else:\n res.append((nums[i], nums[l], nums[r]))\n while l < r and nums[l] == nums[l+1]:\n l += 1\n while l < r and nums[r] == nums[r-1]:\n r -= 1\n l += 1; r -= 1\n return res
1,424
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
36,615
123
# PYTHON CODE\n\n```\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]: \n nums.sort() # sorting cause we need to avoid duplicates, with this duplicates will be near to each other\n l=[]\n for i in range(len(nums)): #this loop will help to fix the one number i.e, i\n if i>0 and nums[i-1]==nums[i]: #skipping if we found the duplicate of i\n continue \n\t\t\t\n\t\t\t#NOW FOLLOWING THE RULE OF TWO POINTERS AFTER FIXING THE ONE VALUE (i)\n j=i+1 #taking j pointer larger than i (as said in ques)\n k=len(nums)-1 #taking k pointer from last \n while j<k: \n s=nums[i]+nums[j]+nums[k] \n if s>0: #if sum s is greater than 0(target) means the larger value(from right as nums is sorted i.e, k at right) \n\t\t\t\t#is taken and it is not able to sum up to the target\n k-=1 #so take value less than previous\n elif s<0: #if sum s is less than 0(target) means the shorter value(from left as nums is sorted i.e, j at left) \n\t\t\t\t#is taken and it is not able to sum up to the target\n j+=1 #so take value greater than previous\n else:\n l.append([nums[i],nums[j],nums[k]]) #if sum s found equal to the target (0)\n j+=1 \n while nums[j-1]==nums[j] and j<k: #skipping if we found the duplicate of j and we dont need to check \n\t\t\t\t\t#the duplicate of k cause it will automatically skip the duplicate by the adjustment of i and j\n j+=1 \n return l\n```\n\n# JAVA CODE\n\n```\nclass Solution {\n public List<List<Integer>> threeSum(int[] nums) { \n List<List<Integer>> arr = new ArrayList<>();\n Arrays.sort(nums);\n for (int i=0; i<nums.length; i++){\n if (i>0 && nums[i] == nums[i-1]){\n continue;\n }\n int j = i+1;\n int k = nums.length - 1;\n while (j<k){\n int s = nums[i]+ nums[j]+ nums[k];\n if (s > 0){\n k -= 1;\n }\n else if (s < 0){\n j += 1;\n }\n else{\n arr.add(new ArrayList<>(Arrays.asList(nums[i],nums[j],nums[k]))); \n j+=1;\n while (j<k && nums[j] == nums[j-1]){\n j+=1;\n }\n }\n }\n }\n return arr;\n }\n}\n```\n**PLEASE UPVOTE IF YOU FOUND THE SOLUTION HELPFUL**
1,425
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
42,506
464
This problem stumped me for a long time, even though in principle it should be similar to the 2-sum problem. So I littered it with comments since I couldn\'t understand it any other way.\n\nI hope this ends up being useful to someone else!\n\n```\nfunction threeSum(nums) {\n\tconst results = []\n\n\t// obviously irrelevant if we don\'t have at least 3 numbers to play with!\n\tif (nums.length < 3) return results\n\n\t// having the numbers in ascending order will make this problem much easier.\n\t// also, knowing the overall problem will take at least O(N^2) time, we can\n\t// afford the O(NlogN) sort operation\n\tnums = nums.sort((a, b) => a - b)\n\n // if the question asks us for a custom target, we can control it here\n\tlet target = 0\n\n\tfor (let i = 0; i < nums.length - 2; i++) {\n\t\t// `i` represents the "left" most number in our sorted set.\n\t\t// once this number hits 0, there\'s no need to go further since\n\t\t// positive numbers cannot sum to a negative number\n\t\tif (nums[i] > target) break\n\n\t\t// we don\'t want repeats, so skip numbers we\'ve already seen\n\t\tif (i > 0 && nums[i] === nums[i - 1]) continue\n\n\t\t// `j` represents the "middle" element between `i` and `k`.\n\t\t// we will increment this up through the array while `i` and `k`\n\t\t// are anchored to their positions. we will decrement `k` for\n\t\t// for each pass through the array, and finally increment `i`\n\t\t// once `j` and `k` meet.\n\t\tlet j = i + 1\n\n\t\t// `k` represents the "right" most element\n\t\tlet k = nums.length - 1\n\t\t\n\t\t// to summarize our setup, we have `i` that starts at the beginning,\n\t\t// `k` that starts at the end, and `j` that races in between the two.\n\t\t//\n\t\t// note that `i` is controlled by our outer for-loop and will move the slowest.\n\t\t// in the meantime, `j` and `k` will take turns inching towards each other depending\n\t\t// on some logic we\'ll set up below. once they collide, `i` will be incremented up\n\t\t// and we\'ll repeat the process.\n\n\t\twhile (j < k) {\n\t\t\tlet sum = nums[i] + nums[j] + nums[k]\n\n\t\t\t// if we find the target sum, increment `j` and decrement `k` for\n\t\t\t// other potential combos where `i` is the anchor\n\t\t\tif (sum === target) {\n\t\t\t\t// store the valid threesum\n\t\t\t\tresults.push([nums[i], nums[j], nums[k]])\n\n\t\t\t\t// this is important! we need to continue to increment `j` and decrement `k`\n\t\t\t\t// as long as those values are duplicated. in other words, we wanna skip values\n\t\t\t\t// we\'ve already seen. otherwise, an input array of [-2,0,0,2,2] would result in\n\t\t\t\t// [[-2,0,2], [-2,0,2]].\n\t\t\t\t//\n\t\t\t\t// (i\'m not a fan of this part because we\'re doing a while loop as we\'re\n\t\t\t\t// already inside of another while loop...)\n\t\t\t\twhile (nums[j] === nums[j + 1]) j++\n\t\t\t\twhile (nums[k] === nums[k - 1]) k--\n\n\t\t\t\t// finally, we need to actually move `j` forward and `k` backward to the\n\t\t\t\t// next unique elements. the previous while loops will not handle this.\n\t\t\t\tj++\n\t\t\t\tk--\n\n\t\t\t// if the sum is too small, increment `j` to get closer to the target\n\t\t\t} else if (sum < target) {\n\t\t\t\tj++\n\n\t\t\t// if the sum is too large, decrement `k` to get closer to the target\n\t\t\t} else { // (sum > target)\n\t\t\t\tk--\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results\n};\n```
1,428
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
4,125
16
/*question me apko ek array dia h or bola h find kro asse 3 number jinka sum 0 ho to hmne kya kia iska ek \nbrute force -: approach ye ho skta tha ki hum ek loop ko 3 bar chla de or usme sum krke dekhle kya sum = 0 ha ye hogai n cube vali approach(N^3) jo shi nhi h to abb kya kr skte h ya to ek kam kro do loop chlao or dono ka sum krlo fir check krlo kya 3rd element hmari map me present ha kya ; ye hoga n square log n or space bhi lgega \n\nbest part ye kr skte h ji hmne ek sum nikal lia vo kya hoga vhi elemet hoga kyuki chlo example se smjha te h\n\nmnlo array dia h jo ki h array 1 =[-1,0,1,2,-1,-4] to hmne kya kia isko sort krdia to vo sort hoke aya \n[-4,-1,-1,0,1,2] to abhi hmne kya kia apni ek sum variable lia \nsum = 0-nums[i] first step yani ki -4 ke lai value aai 4 to abhi hmne kya kai ek low pointer lia ek high pointer lia low liaa h i+1 se or high lia h nums.size()-1\n\nyani ki hmne kya le lai h ek sum le lai h vo h 4 abb hme do asse number chaiye jinka sum krke 4 aae or agar mil jae to unhe ek vector me store kralo or then ek vector of vector me push krdo ans vali me \n\nabb jo do pointer lie ho unke sath kuch iss tarah khelna h tumhe jse agar low or high ki value apke sum ke brabar h to idrectly store krdo ji nhi h to ya to choti hogi ya to bdi hogi \n\nagar low or high ki value sum se choti h to apko pta h apki array already sorted h ji sirf low ko agge bdao highko mt chedo \nagar apki value sum ki bdi h low or high ke sum se to high ko piche lao ji \nor last me while loww ko low++ krna or \n\nhigh ko high-- krna mt bhulna if condition me hi or ha ek or chiz taki hme repatedly checkna krna pde mnlo sum chaiye 4 or hmara arrah h 2 to hum kya krre h low ko bdare h to low ko asse bdana taki vapas sum kro to vhi 2 hi na aae yani ki low ko itna agge le jao ki abb low ki value vhi nhi h \n\n while(low<high && nums[low] == nums[low+1])\n low++; \n while(low<high && nums[high] == nums[high-1])\n high--;\n*/\n\nclass Solution {\npublic:\n\n\n\n vector<vector<int>> threeSum(vector<int>& nums) {\n vector<vector<int>>ans;\n sort(nums.begin() , nums.end());\n for(int i= 0 ; i<nums.size()-2; i++){\n \n if(i == 0 || (i>0 && nums[i]!= nums[i-1])){\n \n //kyuki agar i = 0 ha to hum i-1 nhi lga skte h na boss isleye hmne kya kai hmne condition dal di ha agar i = 0 ha to sidhe chle jao nhi h to check krlo kya i or i-1 eleent same to nhi h kyuki agar vo same h to koi faida nhi h same ke lia bar bar check krne se \n \n int low = i+1;\n int high = nums.size()-1;\n int sum = 0 - nums[i];\n while(low < high){\n \n if(nums[low] + nums[high] == sum){\n vector<int>x;\n x.push_back(nums[i]);\n x.push_back(nums[low]);\n x.push_back(nums[high]);\n ans.push_back(x);\n \n while(low<high && nums[low] == nums[low+1])\n low++; \n while(low<high && nums[high] == nums[high-1])\n high--;\n \n low++; high--;\n }\n \n else if (nums[low] + nums[high] < sum){\n low++;\n }\n else\n high--;\n }\n \n }\n }\n return ans;\n }\n};
1,444
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
24,607
50
# Approach\n<!-- Describe your approach to solving the problem. -->\nMake a list of set and then iterate over nums array and then use two pointer method to find the sum of all the three numbers required and if the sum is equal to zero then make a new ArrayList and store all the three numbers in it and then store that ArrayList in the set of list.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2)$$\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> threeSum(int[] nums) {\n Arrays.sort(nums);\n Set<List<Integer>> ans=new HashSet<>();\n for(int i = 0; i < nums.length-2; i++){\n int p1 = i+1;\n int p2 = nums.length-1;\n while(p1 < p2){\n int sum = nums[i]+nums[p1]+nums[p2];\n if(sum == 0){\n ArrayList<Integer> sp = new ArrayList<>();\n sp.add(nums[i]);\n sp.add(nums[p1]);\n sp.add(nums[p2]);\n \n ans.add(sp);\n p1++;\n }\n else if(sum < 0){\n p1++;\n }\n else{\n p2--;\n }\n }\n }\n return new ArrayList<>(ans);\n }\n}\n```
1,445
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
1,018
6
**If you like Please Upvote.**\n\n![image]()\n
1,446
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
522
7
```\nvector<vector<int>> threeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n vector<vector<int>>ans;\n for(int i=0;i<nums.size();i++){\n if(i>0 && nums[i]==nums[i-1])continue; //to remove any duplicate at the first number\n int target=-nums[i];\n int j=i+1;\n int k=nums.size()-1;\n while(j<k){\n int sum=nums[j]+nums[k];\n if(sum<target)j++;\n else if(sum>target)k--;\n else{\n ans.push_back({nums[i],nums[j],nums[k]});\n while(j<nums.size()-1 && nums[j]==nums[j+1])j++; //remove duplicate in the 2nd number\n while(k>0 && nums[k]==nums[k-1])k--; //remove duplicate in the 3rd number\n j++,k--;\n }\n }\n }\n return ans;\n }\n```
1,447
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
210
5
```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end()); // Sorting the input array in ascending order\n vector<vector<int>> v; // Vector to store the triplets that sum to zero\n\n // Loop through the array, considering each element as a potential starting point of a triplet\n for(int i = 0; i < n - 2; i++) {\n\n // Skip duplicates to avoid duplicate triplets\n if(i > 0 and nums[i] == nums[i-1]) continue;\n\n int tar = -(nums[i]); // Target value to achieve in the remaining array\n int l = i + 1, h = n - 1; // Pointers for the remaining part of the array\n\n // Iterate through the remaining array using two pointers\n while(l < h) {\n \n // Skip duplicates to avoid duplicate triplets\n if(l > i + 1 and nums[l] == nums[l-1]) {\n l++;\n continue;\n }\n\n int curr = nums[i] + nums[l] + nums[h]; // Calculate the current sum\n\n if(curr == 0) {\n // If the sum is zero, add the triplet to the result vector\n v.push_back({nums[i], nums[l], nums[h]});\n l++; // Move the left pointer to the right\n } else if(curr < 0) {\n l++; // If the sum is less than zero, move the left pointer to the right\n } else {\n h--; // If the sum is greater than zero, move the right pointer to the left\n }\n }\n }\n\n return v; // Return the vector of triplets\n}\n\n};\n\n\n////**** Approch 2 by using set and map ****/////\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) { \n int n =nums.size(); \n sort(nums.begin(), nums.end());\n vector<vector<int>> ans;\n for(int j=0; j<n; j++) {\n if(j != 0 && nums[j] == nums[j-1]) { continue; }\n int target = 0 - nums[j];\n unordered_map<int, int> mp;\n for(int i=j+1; i<n; i++) {\n if(mp.find(target-nums[i]) != mp.end()) {\n vector<int> tempTrip = { nums[j], nums[i], target-nums[i]};\n sort(tempTrip.begin(), tempTrip.end());\n ans.push_back(tempTrip);\n while(i+1< n && nums[i+1] == nums[i]) { i++; }\n }\n mp[nums[i]] = i;\n }\n \n }\n return ans;\n }\n \n \n\n};\n\n\n```\n\n
1,448
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
1,415
5
## Brute force approach\n\n### Code\n```python\n# Brute Force\n# TC: O(n*n*n)\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n arrLength = len(nums)\n\n ans = []\n\n\n for i_idx in range(0, arrLength - 2):\n for j_idx in range(i_idx + 1, arrLength - 1):\n for k_idx in range(j_idx + 1, arrLength):\n if nums[i_idx] + nums[j_idx] + nums[k_idx] == 0:\n # Sort the triplet and add it to the result if not already present\n triplet = sorted([nums[i_idx], nums[j_idx], nums[k_idx]])\n \n if triplet not in ans:\n ans.append(triplet)\n\n return ans\n```\n\n## Two Pointer (Optimised)\n\n### Code\n```python\n# TC: O(n*n):\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n arrLength = len(nums)\n\n nums.sort()\n\n ans = []\n\n for idx in range(0, arrLength):\n if idx > 0 and nums[idx] == nums[idx-1]:\n continue\n\n start, end = idx + 1, arrLength - 1\n \n while start < end:\n threeSum = nums[idx] + nums[start] + nums[end]\n\n if threeSum == 0:\n ans.append([nums[idx], nums[start], nums[end]])\n \n while (start < end) and nums[start] == nums[start + 1]:\n start += 1\n \n while (start < end) and nums[end] == nums[end - 1]:\n end -= 1\n\n start += 1\n end -= 1\n\n elif threeSum < 0:\n start += 1\n \n else:\n end -= 1\n\n return ans\n```
1,451
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
2,287
14
# Approach: Brute Force (TLE)\nFirst of all we will try by the naive approach,\n1. Create a set of vector triplet to make sure all three triplets are unique.\n2. Run 3 loops of `i, j, k` to iterate over the array.\n3. The triplet is valid if the values add upto 0.\n4. Insert the valid triplet in the set.\n5. After iterating over the array, iterate over the set to push the triplets in the `ans` vector.\n\nThis approach results in **TLE**.\n\n# Complexity\n- Time complexity: $$O(n^3 log(n))$$\n\n- Space complexity: $$O(n)$$\n# Code\n\n```cpp\nclass Solution\n{\n bool _(int a, int b, int c)\n {\n return a + b + c == 0;\n }\n public:\n vector<vector < int>> threeSum(vector<int> &nums)\n {\n vector<vector < int>> ans;\n set<vector < int>> S;\n int n = nums.size();\n\n for (int i = 0; i < n; ++i)\n {\n for (int j = i + 1; j < n; ++j)\n {\n for (int k = j + 1; k < n; ++k)\n {\n if (_(nums[i], nums[j], nums[k]))\n {\n vector<int> v(3);\n v[0] = nums[i];\n v[1] = nums[j];\n v[2] = nums[k];\n sort(v.begin(), v.end());\n S.insert(v);\n }\n }\n }\n }\n\n for (auto v: S) ans.push_back(v);\n\n return ans;\n }\n};\n```\n# Approach: Two Pointer (A/C)\n1. Sort the array `nums`\n2. Run a loop of `i` to iterate over the array.\n3. Use `nums[i]` as the pivot element.\n4. Now create two pointers `low` and `high`, where `low` is positioned at `i+1` and `high` at the end of the array i.e.) `n-1`.\n5. If the triplet (`nums[i]`, `nums[low]`, `nums[high]`) sums upto 0, sort the triplet and push it in `ans` vector.\n6. To make sure no duplicate triplet is pushed in the answer vetor, decrease `high` and increase `low` until you have reached another distinct element.\n7. If the triplet sums to greater than 0, decrease the `high` pointer.\n8. If the triplet sums to less than 0, increase the `low` pointer.\n9. To maintain distinct pivot elements, increase `i` till it reaches the next distinct element.\n\n\n# Complexity\n- Time complexity: $$O(n log(n))$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution\n{\n int _(int a, int b, int c)\n {\n return a + b + c == 0 ? 0 : a + b + c > 0 ? 1 : -1;\n }\n public:\n vector<vector<int>> threeSum(vector<int> &nums)\n {\n vector<vector<int>> ans;\n int n = nums.size();\n sort(nums.begin(), nums.end());\n\n for (int i = 0; i < n - 2; ++i)\n {\n int low = i + 1, high = n - 1;\n while (low < high)\n {\n int a = nums[i], b = nums[low], c = nums[high];\n if (_(a, b, c) == 0)\n {\n vector<int> v(3);\n v[0] = a, v[1] = b, v[2] = c;\n sort(v.begin(), v.end());\n ans.push_back(v);\n while (high > low && nums[high] == nums[high - 1]) --high;\n while (low < high && nums[low] == nums[low + 1]) ++low;\n --high, ++low;\n }\n else if (_(a, b, c) == 1)\n --high;\n else\n ++low;\n }\n while (i < n - 1 && nums[i] == nums[i + 1]) ++i;\n }\n\n return ans;\n }\n};\n```\nPlease upvote if helped \uD83D\uDE0A
1,452
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
10,599
121
first of all sort the array so that you will apply my approach of two pointers.\n\ntraverse the whole array.\n\nif there is duplicate of an element in an array then simply go to the next element thats why i write this step.\n**if(i>0 && nums[i]==nums[i-1])**\n {\n continue;\n }\nthen make two pointer first is i+1 and other is the last element .\n\ncheck that if sum of all nums[i]+nums[low]+nums[high]=0.\nthen simply insert it in the 2-d vector.\n\n\nif nums[low] has a duplicate value the simply increment the value of low that\'s why i have writtened the step.\n\n** int val1=nums[j];\n while(j<k && nums[j]==val1)\n j++;**\n\t\t\t\t\t\n\t\t\t\t\t\nsimilarly for high if there is any dulicate value of nums[high] then simply decremenet the value of high.\n\n** int val2=nums[k];\n while(j<k && nums[k]==val2)\n k--;**\n\t\t\t\t\t\n**lastly check if the sum of all three nums[i],nums[low],nums[high] is less than 0\nthen simply increment low pointer.\nnow this is the main reason behind that sorting of vector.\ncheck if the sum of all three nums[i],nums[low],nums[high] is greater than 0\nthen simply decrement high pointer**.\n\n\n\nvector<vector<int>> threeSum(vector<int>& nums) {\n \n vector<vector<int>> v;\n \n \n sort(nums.begin(),nums.end());\n \n \n \n for(int i=0;i<nums.size();i++)\n {\n if(i>0 && nums[i]==nums[i-1]) continue;\n int j=i+1, k=nums.size()-1;\n \n \n while(j<k){\n \n if(nums[i]+nums[j]+nums[k]==0)\n {\n v.push_back({nums[i],nums[j],nums[k]});\n \n \n int val1=nums[j];\n while(j<k && nums[j]==val1) j++;\n \n \n int val2=nums[k];\n while(j<k && nums[k]==val2) k--;\n \n }\n \n else if(nums[i]+nums[j]+nums[k]<0) j++;\n \n \n \n else if(nums[i]+nums[j]+nums[k]>0) k--;\n \n }\n }\n \n \n return v;\n }\n\t\n\t//keep coding Guys \n\t// Happy coding \n\t\n\t// Guys plz plz plz upvote my solution if you really understands and like it .and comment if you have any doubt.\n\n\n\n
1,453
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
3,485
7
\n\n# Approach\n- Sort the input array nums in ascending order. This allows us to easily eliminate duplicate values and manipulate the pointers efficiently.\n- Iterate over the sorted array using a loop. Let the current index be i.\n- Inside the loop, handle duplicate values. If i is greater than zero and the current element is the same as the previous element, skip to the next iteration.\n- Initialize two pointers: j pointing to the element after i, and k pointing to the last element in the array.\n- Enter a while loop with the condition j < k. This loop will continue until the pointers meet.\n- Calculate the sum of the elements at indices i, j, and k: sum = nums[i] + nums[j] + nums[k].\n- If sum is less than zero, increment j to move towards higher values.\n- If sum is greater than zero, decrement k to move towards lower values.\n- If sum is equal to zero, we have found a valid triplet. Create a temporary vector temp and store the values nums[i], nums[j], and nums[k] in it. Add temp to the final result vector ans.\n- Increment j and decrement k to continue searching for more triplets.\n- Handle duplicate values by skipping over them. If j is still less than k and the current element is the same as the previous element, increment j and decrement k again.\n- Once the while loop ends, continue with the next iteration of the outer loop, incrementing i.\n- After all iterations, return the final result vector ans.\n\nThis approach ensures that we cover all possible triplets that sum up to zero while avoiding duplicates. \n\n# Complexity\n- Time complexity:\nO(nlog(n)) + O(n*n)\nnlog(n) for sorting the array and n*n for finding the triplets\n\n- Space complexity:\nO(1). We do use O(no. of unique triplets for storing the answer)\n\n# C++ Code\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n vector<vector<int>> ans;\n sort(nums.begin(), nums.end());\n for(int i = 0; i< nums.size(); i++){\n if(i >0 && nums[i] == nums[i-1]) continue;\n int j = i+1;\n int k = nums.size()-1;\n while(j<k){\n int sum = nums[i]+nums[j]+nums[k];\n if(sum<0){\n j++;\n }\n else if(sum>0){\n k--;\n }\n else {\n vector<int> temp = {nums[i], nums[j], nums[k]};\n ans.push_back(temp);\n j++;\n k--;\n while(j<k && nums[j] == nums[j-1]) j++;\n while(j<k && nums[k] == nums[k+1]) k--;\n }\n }\n }\n return ans;\n }\n};\n```\n# JAVA Code\n```\nclass Solution {\n public List<List<Integer>> threeSum(int[] nums) {\n List<List<Integer>> ans = new ArrayList<>();\n Arrays.sort(nums);\n \n for (int i = 0; i < nums.length; i++) {\n if (i > 0 && nums[i] == nums[i - 1]) continue; \n int j = i + 1;\n int k = nums.length - 1;\n while (j < k) {\n int sum = nums[i] + nums[j] + nums[k];\n if (sum < 0) {\n j++; \n } else if (sum > 0) {\n k--; \n } else {\n List<Integer> temp = new ArrayList<>();\n temp.add(nums[i]);\n temp.add(nums[j]);\n temp.add(nums[k]);\n ans.add(temp);\n j++; \n k--; \n while (j < k && nums[j] == nums[j - 1]) j++; \n while (j < k && nums[k] == nums[k + 1]) k--; \n }\n }\n }\n return ans;\n }\n}\n```\n
1,454
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
1,440
9
**1. Using Two Pointer Approach**\n* Pre-requisites : [Two Sum]() , [Two Sum II]() (For Better Understanding)\n* Time Complexity : O(N^2)\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int n = nums.size();\n \n // initializing start, end and sum\n int s, e, sum = 0;\n vector<vector<int>> ans;\n sort(nums.begin(), nums.end());\n \n // for loop to fix the first element of the triplet\n for(int i = 0; i < n; i++){\n //if the very first element of the array is greater than 0(which is smallest element after sorting), then triplet cannot be formed\n if(nums[i] > 0){\n break;\n }\n \n // to avoid duplicacy skip the iteration if to adjacent element are equal\n if(i > 0 && nums[i] == nums[i-1]){\n continue;\n }\n \n //After fixing first element, we are left with TWO SUM problem\n s = i + 1; \n e = n - 1;\n while(s < e){\n sum = nums[i] + nums[s] + nums[e];\n if(sum < 0){\n s++;\n }\n else if(sum > 0){\n e--;\n }\n else{\n ans.push_back({nums[i], nums[s], nums[e]});\n s++, e--;\n \n //increment s and e, to the new positions\n while(s < e && nums[s] == nums[s-1])\n s++;\n while(s < e && nums[e] == nums[e+1])\n e--;\n }\n }\n }\n \n return ans;\n }\n};\n```\n\nPlease Upvote if it helps you :)\n
1,457
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
869
6
So from the given array we have to find 3 elements such that their sum must be equal to 0, also the elements cannot be same and also cannot be from the same index, \nSo the brute force way to do this would take around 0(n^3) time complextiy here\'s how you can do it in 0(n^2) \nSo as we know the 2 pointer method where we traverse the array from start and end at the same time, we are going to use somewhat similar method \nStep 1 . Sort the array using inbuilt sort() function, for each element we will find the 2 elements that will create our desired sum, `i` will be the index that starts from 0 and we will have 2 more indexes called as `left` and `right` which will start from i+1 and nums.size()-1 respectively \n\nStep 2. Inside the for loop that runs from 0 ... n-1 for every i u have to check if nums[i]+nums[left]+nums[right] == 0, if so add them to our output vector and increment left such that the next left shouldn\'t be same as current left(as we need to have unique values) and also left < right, same thing for right decrement right such that the next right shouldn\'t be same as the current right and left<right should be true\nif nums[i]+nums[left]+nums[right] < 0 we have to do left++, if >0 we have right--\n\nsteo 3. Once left<right becomes false in step 2 that means for that i we have computed all the possiblities, increment i such that i++ wont be equal to current i as the given array cant have duplicate values, repeat the same process for every `i` \n\nBelow is the code for reference after reading the explanation you should have the intuition about the problem and can understand the code easily\n\n```\nvector<vector<int>> threeSum(vector<int>& nums) {\n vector<vector<int>> output ;\n sort(nums.begin(),nums.end());\n for(int i=0; i<nums.size();i++){\n int left = i+1 ;\n int right = nums.size()-1;\n while(left < right){\n if(nums[i]+nums[left]+nums[right] == 0){\n output.push_back({nums[i],nums[left],nums[right]});\n int x = nums[left] ;\n int y = nums[right] ;\n while(left<right && nums[left] ==x){\n left++ ;\n }\n while(left<right && nums[right] ==y){\n right-- ;\n }\n }else if(nums[i]+nums[left]+nums[right] > 0){\n right --;\n }else {\n left ++;\n }\n }\n while(i+1 < nums.size() && nums[i] == nums[i+1]){\n i++;\n }\n }\n return output ;\n }\n\t```
1,458
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
2,122
16
vector<vector<int>> threeSum(vector<int>& nums) {\n \n vector<vector<int>> res;\n\n sort(nums.begin(),nums.end());\n \n for(int i = 0; i < nums.size();i++) {\n\n if((i > 0) && nums[i]==nums[i-1])\n continue;\n \n int l = i + 1; \n int r = nums.size() - 1; \n \n while (l < r) {\n \n int sum = nums[i] + nums[l] + nums[r];\n \n if(sum < 0)\n l++;\n else\n if(sum > 0)\n r--;\n else\n if(sum == 0) {\n res.push_back(vector<int>{nums[i],nums[l],nums[r]});\n \n while (l<r && nums[l] == nums[l+1]) \n l++;\n\n while (l<r && nums[r] == nums[r-1]) \n r--;\n l++;\n r--;\n }\n }\n }\n return res;\n }\n};\npls upvote if u find it helpful, nhi to koi na
1,467
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
18,624
61
# without sort\n```\n //Runtime: 384 ms, faster than 24.18% of Java online submissions for 3Sum.\n //Memory Usage: 120.2 MB, less than 15.92% of Java online submissions for 3Sum.\n //without sort\n //Time: O(N * N * log3); Space:O(N)\n public List<List<Integer>> threeSum(int[] nums) {\n Set<List<Integer>> resultSet = new HashSet();\n\n Set<Integer> duplicatedSet = new HashSet<>();\n Map<Integer, Integer> map = new HashMap<>();\n\n for(int i = 0; i < nums.length - 2; i++) {\n if (!duplicatedSet.add(nums[i])) continue;\n\n for (int j = i + 1; j < nums.length; j++) {\n int value = 0 - nums[i] - nums[j];\n if (map.containsKey(value) && map.get(value) == i) {\n List<Integer> list = new ArrayList<>(Arrays.asList(nums[i], nums[j], value));\n Collections.sort(list);\n resultSet.add(list);\n }\n map.put(nums[j], i);\n }\n }\n return new ArrayList<>(resultSet) ;\n }\n```\n\n# Two pointers\n```\n\n //Runtime: 47 ms, faster than 35.83% of Java online submissions for 3Sum.\n //Memory Usage: 60.1 MB, less than 32.20% of Java online submissions for 3Sum.\n //Two pointers\n //Time: O(N * LogN + N * N); Space : O(N + LogN)\n public List<List<Integer>> threeSum(int[] nums) {\n Set<List<Integer>> resultSet = new HashSet();\n Arrays.sort(nums);\n\n for(int i = 0; i <= nums.length - 3 && nums[i] <= 0;){\n int left = i + 1, right = nums.length - 1;\n if (0 - nums[i] - nums[left] < 0) break;\n\n while (left < right) {\n int sum = nums[i] + nums[left] + nums[right];\n if (sum > 0) {\n right--;\n while (left < right && nums[right] == nums[right + 1]) right--; //skip duplicated number\n } else {\n if (sum == 0) {\n resultSet.add(Arrays.asList(nums[i], nums[left], nums[right]));\n right--;\n while (left < right && nums[right] == nums[right + 1]) right--;\n }\n left++;\n while (left < right && nums[left] == nums[left - 1]) left++;\n }\n }\n i++;\n while(i < nums.length - 2 && nums[i] == nums[i - 1]) i++;\n }\n return new ArrayList<>(resultSet);\n }\n```\n# Binary Search\n```\n\n //Runtime: 99 ms, faster than 29.77% of Java online submissions for 3Sum.\n //Memory Usage: 60.2 MB, less than 31.74% of Java online submissions for 3Sum.\n //Binary Search\n //Time: O(N * logN + N * N * logN); Space:O(N + LogN)\n public List<List<Integer>> threeSum_3(int[] nums) {\n Set<List<Integer>> resultSet = new HashSet();\n Arrays.sort(nums);\n\n for(int i = 0; i < nums.length - 2 && nums[i] <= 0;){\n for (int j = i + 1; j < nums.length && nums[i] + nums[j] <= 0;) {\n int value = 0 - nums[i] - nums[j];\n if (value < 0) return new ArrayList<>(resultSet);\n int idx = Arrays.binarySearch(nums, j + 1, nums.length, value);\n if (idx >= 0)\n resultSet.add(Arrays.asList(nums[i], nums[j], value));\n j++;\n while (j < nums.length && nums[j] == nums[j - 1]) j++;\n }\n i++;\n while(i < nums.length - 2 && nums[i] == nums[i - 1]) i++;\n }\n return new ArrayList<>(resultSet);\n }\n```\n# HashMap\n```\n\n //Runtime: 106 ms, faster than 29.54% of Java online submissions for 3Sum.\n //Memory Usage: 70.8 MB, less than 23.87% of Java online submissions for 3Sum.\n //HashMap\n //Time:O(N * logN + N * N); Space: O(N + logN + N)\n public List<List<Integer>> threeSum_2(int[] nums) {\n Set<List<Integer>> resultSet = new HashSet();\n Arrays.sort(nums);\n Map<Integer, Integer> map = new HashMap<>();\n for(int i = 0; i < nums.length; i++) map.put(nums[i], i);\n\n for(int i = 0; i < nums.length - 2 && nums[i] <= 0;){\n for (int j = i + 1; j < nums.length && nums[i] + nums[j] <= 0;) {\n int value = 0 - nums[i] - nums[j];\n //if (value < 0) break;\n if (value < 0) return new ArrayList<>(resultSet);\n if (value < nums[j]) break;\n if (map.containsKey(value) && map.get(value) > j)\n resultSet.add(Arrays.asList(nums[i], nums[j], value));\n j++;\n while(j < nums.length && nums[j] == nums[j - 1]) j++;\n }\n i++;\n while(i < nums.length - 2 && nums[i] == nums[i - 1]) i++;\n }\n return new ArrayList<>(resultSet) ;\n }\n```\n# brute force\n```\n\n //TLE\n //brute force\n //Time: O(N * N * N * log3); Space: O(N)\n public List<List<Integer>> threeSum_brute(int[] nums) {\n Set<List<Integer>> resultSet = new HashSet();\n for (int i = 0; i < nums.length - 2; i++)\n for (int j= i + 1; j < nums.length - 1; j++)\n for (int k = j + 1 ; k < nums.length; k++)\n if (0 == nums[i] + nums[j] + nums[k]) {\n List<Integer> list = new ArrayList<>(Arrays.asList(nums[i], nums[j], nums[k]));\n Collections.sort(list);\n resultSet.add(list);\n }\n return new ArrayList<>(resultSet);\n }\n\t\n```
1,469
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
1,977
7
# Approach 1\nBrute-Force\n\n# Complexity\n- Time complexity:\n$$O(n^3*logk)$$ --> k is no. of unique triplets\n\n- Space complexity:\n$$O(k)$$ --> k is no. of unique triplets\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int n = nums.size();\n set<vector<int>> st;\n for (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n for (int k = j+1; k < n; k++) {\n if (nums[i] + nums[j] + nums[k] == 0) {\n vector<int> temp = {nums[i], nums[j], nums[k]};\n sort(temp.begin(), temp.end());\n st.insert(temp); \n }\n }\n }\n }\n vector<vector<int>> triplet(st.begin(), st.end());\n return triplet;\n }\n};\n```\n\n# Approach 2\nBetter\n\n# Complexity\n- Time complexity:\n$$O(n^2*logn*logk)$$ --> k is no. of unique triplets\n\n- Space complexity:\n$$O(n+k)$$ --> k is no. of unique triplets\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int n = nums.size();\n set<vector<int>> st;\n for (int i = 0; i < n; i++) {\n set<int> s;\n for (int j = i+1; j < n; j++) {\n int third = -(nums[i] + nums[j]);\n if (s.find(third) != s.end()) {\n vector<int> temp = {nums[i], nums[j], third};\n sort(temp.begin(), temp.end());\n st.insert(temp);\n }\n s.insert(nums[j]);\n }\n }\n vector<vector<int>> triplet(st.begin(), st.end());\n return triplet;\n }\n};\n```\n\n# Approach 3\nOptimal - Two Pointer\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n vector<vector<int>> triplet;\n for (int i = 0; i < n; i++) {\n if (i != 0 && nums[i] == nums[i-1])\n continue;\n int j = i+1, k = n-1;\n while (j < k) {\n int sum = nums[i] + nums[j] + nums[k];\n if (sum == 0) {\n vector<int> temp = {nums[i], nums[j], nums[k]};\n triplet.push_back(temp);\n j++;\n k--;\n while (j < k && nums[j] == nums[j-1]) j++;\n while (j < k && nums[k] == nums[k+1]) k--;\n } else if (sum > 0) {\n k--;\n } else {\n j++;\n }\n } \n }\n return triplet;\n }\n};\n```
1,470
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
1,048
6
# Intuition\nJustt like two sum with target = 0, so here we use 3 variables i,j,k and fix i then iterate the vector and check if their sum is equal to target or not if yes then push in the vector else not.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n### Before seeing the code please read the steps carefully as it will help to understand the code more easily.\n\n- Sort the vector in decending order.\n- Start a loop to keep i fixed. Inside it initialize j as i+1 and k as nums.size()-1.\n- Make a nested while loop to control j & k. Whw\n- Check whether the sum of nums[i]+ nums[j]+nums[k] == 0 if yes then push it into the vector of vectors and increase j and decrease k.\n- Now if the sum is less than 0 then increase j else decrease k;\n- Now by this method you will also ge the duplicates so inorder to remove them we use some condiions for i,j & k respectively\n 1. nums[i]>0 then break && if (i!=0 && nums[i]==nums[i-1]) then continue due to which it will not iterate in case of consecutive i\'s with same value.\n 2. Now inside the condiion where sum == 0 we make a while loop and check of same values of j\'s appearing consecutively, If they occur then we increase j.\n 3. Similarly we check for the value of k in the case of sum ==0 and decrease k if consecutive same values are there.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: **$$O(N^2 log N)$$**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **$$O(N)$$**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n vector<vector<int>>s;\n sort(nums.begin(),nums.end());\n int n=nums.size();\n // if(n==3)\n // return {nums};\n for(int i=0;i<n;i++)\n {\n if(nums[i]>0)\n break;\n int j=i+1;\n int k=n-1;\n if(i!=0 && nums[i]==nums[i-1])\n continue;\n while(j<k && nums[k]>=0)\n {\n int sum=nums[i]+nums[j]+nums[k];\n if(sum==0){\n s.push_back({nums[i],nums[j],nums[k]});\n j++;\n k--;\n while(j<k && nums[j]==nums[j-1])j++;\n while(j<k && nums[k]==nums[k+1])k--;\n }\n else if(sum<0)\n j++;\n else\n k--;\n }\n }\n return s;\n }\n};\n```\n![Screenshot 2023-08-07 111948.png]()\n
1,472
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
1,181
9
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe steps are as follows:\n\n1) First, we will sort the entire array.\n\n2) We will use a loop(say i) that will run from 0 to n-1. This i will represent the fixed pointer. In each iteration, this value will be fixed for all different values of the rest of the 2 pointers. Inside the loop, we will first check if the current and the previous element is the same and if it is we will do nothing and continue to the next value of i.\n\n3) After that, there will be 2 moving pointers i.e. j(starts from i+1) and k(starts from the last index). The pointer j will move forward and the pointer k will move backward until they cross each other while the value of i will be fixed.\n\n 1) Now we will check the sum i.e. arr[i]+arr[j]+arr[k].\n 2) If the sum is greater, then we need lesser elements and so we will decrease the value of k(i.e. k\u2013). \n 3) If the sum is lesser than the target, we need a bigger value and so we will increase the value of j (i.e. j++). \n 4) If the sum is equal to the target, we will simply insert the triplet i.e. arr[i], arr[j], arr[k] into our answer and move the pointers j and k skipping the duplicate elements(i.e. by checking the adjacent elements while moving the pointers).\n4) Finally, we will have a list of unique triplets.\n\n![image.png]()\n\n\n\n# Complexity\n- Time complexity:O(NlogN)+O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) - we are not using any extra space \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> threeSum(int[] nums) {\n List<List<Integer>> ans = new ArrayList<>();\n int n = nums.length;\n Arrays.sort(nums);\n for(int i = 0; i<n ; i++ ){\n if(i != 0 && nums[i] == nums[i-1]){\n continue;\n }\n int j =i+1;\n int k = n-1;\n while(j<k){\n int sum = nums[i] + nums[j] + nums[k];\n\n if(sum<0){\n j++;\n }\n else if(sum>0){\n k--;\n }\n else {\n List<Integer> temp = Arrays.asList(nums[i] , nums[j],nums[k]);\n ans.add(temp);\n j++;\n k--;\n while(k>j &&nums[k]== nums[k+1]) k--;\n while(k>j && nums[j]== nums[j-1]) j++;\n }\n }\n }\n return ans;\n }\n}\n```\n\n![image.png]()\n
1,482
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
7,531
9
# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> threeSum(vector<int>& nums) {\n unordered_map<int,int>mp;\n vector<vector<int>>ans;\n set<vector<int>>st;\n vector<int>v;\n for(int i=0;i<nums.size();++i)\n {\n for(int j=i+1;j<nums.size();++j)\n {\n if(i!=j&&mp.find(-nums[i]-nums[j])!=mp.end()&&mp[-nums[i]-nums[j]]!=i&&mp[-nums[i]-nums[j]]!=j)\n {\n v.push_back(nums[i]);\n v.push_back(nums[j]);\n v.push_back(-nums[i]-nums[j]);\n sort(v.begin(),v.end());\n st.insert(v);\n v.clear();\n }\n mp[nums[j]]=j;\n }\n }\n for(auto i:st)\n {\n ans.push_back(i);\n }\n return ans;\n }\n};\n```
1,484
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
14,052
20
# 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 List<List<Integer>> threeSum(int[] nums) {\n Set<List<Integer>> set=new HashSet<>();\n if(nums.length==0) return new ArrayList<>();\n Arrays.sort(nums);\n int sum=0;\n for(int i=0;i<nums.length-2;i++)\n {\n int j=i+1;\n int k=nums.length-1;\n while(j<k)\n {\n sum=nums[i]+nums[j]+nums[k];\n if(sum==0) set.add(Arrays.asList(nums[i],nums[j++],nums[k--]));\n if(sum<0) j++;\n if(sum>0) k--;\n\n }\n }\n return new ArrayList<>(set);\n \n }\n}\n```
1,487
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
100,233
301
**Solution with discussion** \n\n**3Sum** \n\n**Sort based algorithm**\n* a+b = -c. 3SUM reduces to 2SUM problem.\n\n**Handling Duplicates in 2SUM**\n* Say index s and e are forming a solution in a sorted array. Now givens nums[s], there is a unique nums[e] such that nums[s]+nums[e]=Target. Therefore, if nums[s+1] is the same as nums[s], then searching in range s+1 to e will give us a duplicate solution. Thus we must move s till nums[s] != nums[s-1] to avoid getting duplicates.\n```\n while s<e and nums[s] == nums[s-1]:\n s = s+1\n```\n\n**Handling Duplicates in 3SUM**\n* Imagine we are at index i and we have invoked the 2SUM problem from index i+1 to end of the array. Now once the 2SUM terminates, we will have a list of all triplets which include nums[i]. To avoid duplicates, we must skip all nums[i] where nums[i] == nums[i-1].\n```\n if i > 0 and nums[i] == nums[i-1]:\n continue\n```\n\n**Code**\n```\nclass Solution(object):\n def threeSum(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n """\n nums.sort()\n N, result = len(nums), []\n for i in range(N):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n target = nums[i]*-1\n s,e = i+1, N-1\n while s<e:\n if nums[s]+nums[e] == target:\n result.append([nums[i], nums[s], nums[e]])\n s = s+1\n while s<e and nums[s] == nums[s-1]:\n s = s+1\n elif nums[s] + nums[e] < target:\n s = s+1\n else:\n e = e-1\n return result\n```
1,489
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
2,095
7
```\nRuntime: 188 ms, faster than 84.22% of JavaScript online submissions for 3Sum.\nMemory Usage: 52.1 MB, less than 84.25% of JavaScript online submissions for 3Sum.\n\n/* In this problem we need to get the all combinations of three numbers that \ntheir sum adds to \'Zero\', so there is a naive approach of n^3 time complexity where \nwe can have three nested for loops to get the all combinations of every singel numer,\nbut the other approach is n^2 time complexity.\n\nFirst of all we need to sort the array ascendingly and we will know why later. \n\nThen we need to have two pointers, where the first one(left pointer) will start \nfrom i + 1 and the second one(right pointer) will be the index of the array last element.\n\nThen we have a for loop over the whole array and set the left to i + 1;\nright = nums.length - 1 as we mentioned above. \n\nThen we get the sum by adding the first element of the array to the nums[left] + nums[right]. \n\nWe will have three conditions the: \n1. Sum > 0 \n2. Sum < 0 \n3. Sum == 0. \n\nIf the sum > 0 then we need to decrease this sum to get closer to zero \nand get the three numbers so we will decrement the right pointer by one \nbecause we get a less value as we have sorted the array at the first!\n\nIf the sum < 0 then we need to increase this sum to get closer to zero\nand get the three numbers so we will increment the right pointer by one.\n\nIf the sum is equal to zero then those are the three numbers we need so we push \nthem to the empty array \'results\'; not just this we increment the left pointer \nand decrement the right pointer to search for other alternatives.\n\nAnd because we need only unique results when we find that the nums[left] == nums[left+1]\nwhich mean we have two equal adjacents we move the the pointer left ++ and\nthe right also -- so we don\'t have the same triplet pushed to the results array.\n \n*/\n\n\nvar threeSum = function(nums) {\n let result = [];\n\tif(nums.length < 3) return result;\n nums.sort((a, b) => a - b);\n\n for (let i = 0; i < nums.length; i++) {\n if (i > 0 && nums[i] == nums[i - 1]) continue;\n let left = i + 1;\n let right = nums.length - 1;\n\n while (left < right) {\n let sum = nums[i] + nums[left] + nums[right];\n if (sum > 0) {\n right--;\n } else if (sum < 0) {\n left++;\n } else {\n result.push([nums[i], nums[left], nums[right]]);\n while (nums[left] == nums[left + 1]) left++;\n while (nums[right] == nums[right - 1]) right--;\n right--;\n left++;\n }\n }\n\n }\n\n return result;\n}\n
1,490
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
65,029
346
\n vector<vector<int>> threeSum(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n vector<vector<int>> res;\n for (unsigned int i=0; i<nums.size(); i++) {\n if ((i>0) && (nums[i]==nums[i-1]))\n continue;\n int l = i+1, r = nums.size()-1;\n while (l<r) {\n int s = nums[i]+nums[l]+nums[r];\n if (s>0) r--;\n else if (s<0) l++;\n else {\n res.push_back(vector<int> {nums[i], nums[l], nums[r]});\n while (nums[l]==nums[l+1]) l++;\n while (nums[r]==nums[r-1]) r--;\n l++; r--;\n }\n }\n }\n return res;\n }
1,491
3Sum
3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Array,Two Pointers,Sorting
Medium
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
11,283
166
```\n//We declare the list of lists that will contain our solution\n IList<IList<int>> result = new List<IList<int>>();\n\n //The edge case\n if (nums.Length <= 2) return result;\n \n /*For the first, we have to sort the nums*/\n Array.Sort(nums);\n\n /*Here we declare 3 indexes. This is how it works. \n -4 -2 -3 -1 0 0 0 2 3 10 21\n s l r \n \n s - start index, l - left index, r - right index */\n int start = 0, left, right;\n\n /*The target is that the number we are looking for to be composed out of 2 numbers from our array.\n for example, if we have the startIndex at -4, we are looking for those two numbers in the given array\n which, summed up will be the oposite of -4, which is 4, cuz -4 + 4 = 0 (duh) */\n int target;\n\n /*The start goes from 0 to length-2 becuse look here\n -4 -2 -3 -1 0 0 0 2 3 10 21\n s l r */\n while (start<nums.Length-2)\n {\n target = nums[start] * -1;\n left = start + 1;\n right = nums.Length - 1;\n\n /*Now, the start index is fixed and we move the left and right indexes to find those two number\n which summed up will be the oposite of nums[s] */\n while (left < right)\n {\n /*The array is sorted, so if we move to the left the right index, the sum will decrese */\n if (nums[left] + nums[right] > target)\n {\n --right;\n }\n\n /*Here is the oposite, it the sum of nums[l] and nums[r] is less that what we are looking for,\n then we move the left index, which means that the sum will increase due to the sorted array.\n the left index will jump to a bigger value */\n else if (nums[left] + nums[right] < target)\n {\n ++left;\n }\n /*If none of those are true, then it means that nums[l]+nums[r] = our desired value */\n else\n {\n /*Here we create the solution and add it to the list of lists which contains the result. */\n List<int> OneSolution = new List<int>() { nums[start], nums[left], nums[right] };\n result.Add(OneSolution);\n\n /*Now, in order to generate different solutions, we have to jump over\n repetitive values in the array. */\n while (left < right && nums[left] == OneSolution[1])\n ++left;\n while (left < right && nums[right] == OneSolution[2])\n --right;\n }\n\n }\n /*Now we do the same thing to the start index. */\n int currentStartNumber = nums[start];\n while (start < nums.Length - 2 && nums[start] == currentStartNumber)\n ++start;\n }\n return result;\n```\nIf it was useful for you, don\'t forget to smash that upvote button <3
1,494
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
6,487
59
# 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)$$ -->O(N^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n![Screenshot_20230205_171246.png]()\n\n\n# Code\n```\nimport java.util.Arrays;\n\nclass Solution {\n public int threeSumClosest(int[] nums, int target) {\n Arrays.sort(nums);\n int closestSum = nums[0] + nums[1] + nums[2]; // Initialize closest sum with the sum of the first three elements\n\n for (int i = 0; i < nums.length - 2; i++) {\n int j = i + 1;\n int k = nums.length - 1;\n\n while (j < k) {\n int sum = nums[i] + nums[j] + nums[k];\n\n if (Math.abs(target - sum) < Math.abs(target - closestSum)) {\n closestSum = sum; // Update closest sum if the current sum is closer to the target\n }\n\n if (sum < target) {\n j++; // Increment j to increase the sum\n } else {\n k--; // Decrement k to decrease the sum\n }\n }\n }\n\n return closestSum;\n }\n}\n\n```
1,501
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
1,653
11
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is a variation of 2Sum and especially 3Sum problem. In 3Sum, we choose a triplet and checks its sum equal to 0(target). here we have to find the sum of triplet closest to target. so use the same approach as we have used in 3Sum problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nfirst thing is to think how you can get closest sum. For this sort the vector for easiness. \nif sum is greater then target, but we need sum closest, that is ,**the minimum sum greater than equal to target** declare min1 variable with **min1 = INT_MAX - 10000;** we did -10000 so that we can get rid of TLE. and same for when sum is smaller than target , that is, **the greatest sum smaller than equal to target** for this declare, **max1 = INT_MIN + 10000** . if sum is equal to target return the sum. \n\nnow the question is which variale min1, max1 we have to return, for this, find the absolute difference of min1, max1 with target and return min1 or max1 as per the minimum diff obtained.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int threeSumClosest(vector<int>& nums, int target) \n {\n int n= nums.size();\n int sum=0, j=0,k=0;\n int max1 = INT_MIN + 10000, min1 = INT_MAX - 10000;\n sort(nums.begin(), nums.end());\n for(int i=0; i< (n-2); i++)\n {\n j= i+1;\n k= n-1;\n while(j < k)\n {\n sum= nums[i] + nums[j] + nums[k];\n \n if(sum == target)\n return sum;\n \n else if(sum>target)\n {\n min1= min(min1, sum);\n k--;\n }\n else if(sum < target)\n {\n max1= max( max1, sum);\n j++;\n }\n }\n }\n // target =10, a=2, b=1;\n\n int a= min1 - target;\n int b= target - max1;\n\n if(a < b)\n return min1;\n else\n return max1;\n }\n};\n```
1,534
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
1,343
6
![Screenshot 2023-07-25 at 10.14.24 AM.png]()\n\n\n## \uD83C\uDF38\uD83E\uDDE9 Problem Statement \uD83E\uDDE9\uD83C\uDF38\n- Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.\n\n- Return the sum of the three integers.\n\n- *You may assume that each input would have **exactly one solution**.*\n\n#### \uD83D\uDD2E Example 1 :- \n```\nInput: nums = [-1,2,1,-4], target = 1\nOutput: 2\nExplanation: The sum that is closest to the target is \n2. (-1 + 2 + 1 = 2).\n\n```\n#### \uD83D\uDD2E Example 2 :- \n```\nInput: nums = [0,0,0], target = 1\nOutput: 0\nExplanation: The sum that is closest to the target is \n0. (0 + 0 + 0 = 0).\n\n```\n\n## \uD83E\uDDE0 Optimal Approach Based on Sorting and Two Pointer\n<!-- Describe your approach to solving the problem. -->\n- The threeSumClosest function takes a vector nums and an integer target as input and returns an integer representing the sum of three elements closest to the target.\n- It starts by sorting the input vector nums in ascending order using sort.\n- Then, it iterates through the vector using a for-loop for each index i from 0 to n - 2, where n is the size of the vector.\n- Inside the loop, it calls the Solve function, which uses a two-pointer approach to find the closest sum for the current index i.\n- The Solve function uses two pointers, L and R, initialized to i + 1 and n - 1, respectively. It moves the pointers towards each other while calculating the sum of three elements (nums[x] + nums[L] + nums[R]) and updating the ans and mx variables based on the difference from the target.\n- After iterating through all possible combinations of three elements, the function returns the final ans, which represents the sum of three elements closest to the target value.\n\n## \uD83E\uDDD1\u200D\uD83D\uDCBB Code \n```\nclass Solution\n{\n\tpublic: int ans = 0;\n\tint mx = INT_MAX;\n\tvoid Solve(vector<int> &nums, int x, int i, int T)\n\t{\n\t\tint n = nums.size();\n\t\tint L = i;\n\t\tint R = n - 1;\n\t\twhile (L < R)\n\t\t{\n\t\t\tint val = (nums[x] + nums[L] + nums[R]);\n\t\t\tif (abs(T - val) < mx)\n\t\t\t{\n\t\t\t\tans = val;\n\t\t\t\tmx = abs(T - val);\n\t\t\t}\n\t\t\telse if (val > T) R--;\n\t\t\telse L++;\n\t\t}\n\t}\n\n\tint threeSumClosest(vector<int> &nums, int target)\n\t{\n\t\tint n = nums.size();\n\t\tsort(nums.begin(), nums.end());\n\t\tfor (int i = 0; i < n - 2; i++)\n\t\t{\n\t\t\tif (i == 0 || nums[i - 1] != nums[i])\n\t\t\t{\n\t\t\t\tSolve(nums, i, i + 1, target);\n\t\t\t}\n\t\t}\n\n\t\treturn ans;\n\t}\n};\n\n```\n\n#### \uD83C\uDF38 Complexity\n- Time complexity : $$O(n^2)$$\n- Space complexity : $$O(1)$$\n\n## \uD83E\uDDD1\u200D\uD83D\uDCBB All Code \n\n- Java\n```\nimport java.util.Arrays;\n\nclass Solution {\n private int ans = 0;\n private int mx = Integer.MAX_VALUE;\n \n private void Solve(int[] nums, int x, int i, int T) {\n int n = nums.length;\n int L = i;\n int R = n - 1;\n while (L < R) {\n int val = (nums[x] + nums[L] + nums[R]);\n if (Math.abs(T - val) < mx) {\n ans = val;\n mx = Math.abs(T - val);\n } else if (val > T) {\n R--;\n } else {\n L++;\n }\n }\n }\n \n public int threeSumClosest(int[] nums, int target) {\n int n = nums.length;\n Arrays.sort(nums);\n for (int i = 0; i < n - 2; i++) {\n if (i == 0 || nums[i - 1] != nums[i]) {\n Solve(nums, i, i + 1, target);\n }\n }\n return ans;\n }\n}\n\n```\n- Python\n```\nclass Solution:\n def __init__(self):\n self.ans = 0\n self.mx = float(\'inf\')\n\n def Solve(self, nums, x, i, T):\n n = len(nums)\n L = i\n R = n - 1\n while L < R:\n val = nums[x] + nums[L] + nums[R]\n if abs(T - val) < self.mx:\n self.ans = val\n self.mx = abs(T - val)\n elif val > T:\n R -= 1\n else:\n L += 1\n\n def threeSumClosest(self, nums, target):\n n = len(nums)\n nums.sort()\n for i in range(n - 2):\n if i == 0 or nums[i - 1] != nums[i]:\n self.Solve(nums, i, i + 1, target)\n return self.ans\n\n```\n- Javascript\n```\nvar threeSumClosest = function(nums, target) {\n nums.sort((a, b) => a - b);\n let n = nums.length;\n let closest_sum = nums[0] + nums[1] + nums[2]; \n for (let i = 0; i < n - 2; i++) {\n let left = i + 1, right = n - 1;\n while (left < right) { \n let sum = nums[i] + nums[left] + nums[right];\n if (sum == target) { \n return sum;\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n if (Math.abs(sum - target) < Math.abs(closest_sum - target)) { \n closest_sum = sum;\n }\n }\n }\n return closest_sum;\n};\n```\n\n
1,538
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
7,081
22
# 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 threeSumClosest(vector<int>& nums, int target) {\n int diff=INT_MAX;\n int ans=0;\n sort(nums.begin(), nums.end());\n for(int i=0;i<nums.size()-2;i++){\n int low=i+1;\n int high=nums.size()-1;\n int first=nums[i];\n while(low<high){\n if(first+nums[low]+nums[high]==target){\n return target;\n }\n else if(abs(first+nums[low]+nums[high]-target)<diff){\n diff=abs(first+nums[low]+nums[high]-target);\n ans=first+nums[low]+nums[high];\n }\n if(first+nums[low]+nums[high]<target){\n low++; \n }\n else{ high--;\n }\n }\n } \n return ans;\n }\n};\n```\nPlease upvote to motivate me to write more solutions\n\n
1,539
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
1,111
9
# Approach\nSorting & Two Pointer \n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int threeSumClosest(vector<int>& nums, int target) {\n int n = nums.size();\n sort (nums.begin(), nums.end());\n int sum = 0, prevDiff = INT_MAX;\n for (int i = 0; i < n - 2; i++) {\n int left = i + 1, right = n - 1;\n while (left < right) {\n int curSum = nums[i] + nums[left] + nums[right];\n int diff = abs (target - curSum);\n if (diff < prevDiff) {\n sum = curSum;\n prevDiff = diff;\n }\n if (target > curSum)\n left++;\n else\n right--; \n }\n }\n return sum;\n }\n};\n```
1,540
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
2,959
9
\n# Code\n```\nclass Solution {\npublic:\n int threeSumClosest(vector<int>& nums, int target) {\nsort(nums.begin(), nums.end());\nint n=nums.size();\nint mn=INT_MAX;\nint ans=0;\n\nfor(int i=0; i<nums.size(); i++){\n int start=i+1;\n int end=n-1;\n while(start<end){\nint sum=nums[i]+nums[start]+nums[end];\nint diff=abs(sum-target);\n\nif(diff<mn){\nmn=diff;\nans=sum;\n }\nif(sum>target)\nend--;\n\nelse start++;\n\n} \n}\n return ans;\n }\n};\n\n\n```
1,547
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
1,890
7
<--------------\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F PLEASE UPVOTE \u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F--------------->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n//<--------------\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F PLEASE UPVOTE \u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F--------------->\nclass Solution {\npublic:\n int threeSumClosest(vector<int>& nums, int target) {\n int calcu = INT_MAX;\n int ans = 0;\n int n = nums.size() ;\n sort( nums.begin() , nums.end() );\n for( int i=0 ; i<n-2 ; i++ )\n {\n int l = i+1 ;\n int r = n-1 ;\n while( l<r )\n {\n int sum = nums[i]+nums[l]+nums[r];\n int temp = abs( sum - target );\n if( temp<calcu )\n {\n calcu = temp ;\n ans = sum;\n }\n if( sum==target )\n {\n return sum;\n }\n else if( sum<target )\n {\n l++;\n }\n else\n {\n r--;\n }\n } \n }\n return ans;\n }\n};\n//<--------------\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F PLEASE UPVOTE \u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F--------------->\n```
1,550
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
635
5
\n# Code\n```\nclass Solution {\npublic:\n int threeSumClosest(vector<int>& nums, int target) {\n sort(nums.begin(), nums.end());\n int df=INT_MAX;\n int ans;\n for(int i=0;i<nums.size()-2;i++)\n {\n int s=i+1;\n int e=nums.size()-1;\n int sum=nums[i]+nums[s]+nums[e];\n while(s<e)\n {\n sum=nums[i]+nums[s]+nums[e];\n if(abs(sum-target)<df)\n {\n df=abs(sum-target);\n ans=sum;\n }\n \n else if(sum<target)\n s++;\n else\n e--; \n }\n while(i+1<nums.size() && nums[i+1]==nums[i])\n i++;\n }\n return ans;\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!!
1,552
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
59,286
475
Sort the vector and then no need to run *O(N^3)* algorithm as each index has a direction to move.\n\nThe code starts from this formation.\n\n ----------------------------------------------------\n ^ ^ ^\n | | |\n | +- second third\n +-first\n\nif *nums[first] + nums[second] + nums[third]* is smaller than the *target*, we know we have to increase the sum. so only choice is moving the second index forward.\n\n ----------------------------------------------------\n ^ ^ ^\n | | |\n | +- second third\n +-first\n\n\nif the *sum* is bigger than the *target*, we know that we need to reduce the *sum*. so only choice is moving '*third*' to backward. of course if the *sum* equals to *target*, we can immediately return the *sum*.\n\n ----------------------------------------------------\n ^ ^ ^\n | | |\n | +- second third\n +-first\n\n\nwhen *second* and *third* cross, the round is done so start next round by moving '*first*' and resetting *second* and *third*.\n\n ----------------------------------------------------\n ^ ^ ^\n | | |\n | +- second third\n +-first\n\nwhile doing this, collect the *closest sum* of each stage by calculating and comparing delta. Compare *abs(target-newSum)* and *abs(target-closest)*. At the end of the process the three indexes will eventually be gathered at the end of the array.\n\n ----------------------------------------------------\n ^ ^ ^\n | | `- third\n | +- second\n +-first\n\nif no exactly matching *sum* has been found so far, the value in *closest* will be the answer.\n\n\n int threeSumClosest(vector<int>& nums, int target) {\n if(nums.size() < 3) return 0;\n int closest = nums[0]+nums[1]+nums[2];\n sort(nums.begin(), nums.end());\n for(int first = 0 ; first < nums.size()-2 ; ++first) {\n if(first > 0 && nums[first] == nums[first-1]) continue;\n int second = first+1;\n int third = nums.size()-1; \n while(second < third) {\n int curSum = nums[first]+nums[second]+nums[third];\n if(curSum == target) return curSum;\n if(abs(target-curSum)<abs(target-closest)) {\n closest = curSum;\n }\n if(curSum > target) {\n --third;\n } else {\n ++second;\n }\n }\n }\n return closest;\n }
1,562
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
6,036
18
# Intuition:\n\nThe problem requires us to find a triplet of numbers in the given array, such that their sum is closest to the given target. We can use the two-pointer approach along with sorting the array to solve this problem.\n\n# Approach:\n\n1. Sort the given array in non-descending order.\n2. Initialize a variable closest_sum to store the closest sum found so far. Set it initially to the sum of first three elements in the sorted array.\n3. Loop over the array from i=0 to i=n-3, where n is the size of the array.\n4. For each i, initialize two pointers, left and right, to i+1 and n-1 respectively.\n5. While left < right, calculate the sum of the current triplet, sum = nums[i] + nums[left] + nums[right].\n6. If sum is equal to the target, we have found the closest sum possible, so we can return it immediately.\n7. If sum is less than target, increment left by 1. This will increase the sum, and we may get a closer sum.\n8. If sum is greater than target, decrement right by 1. This will decrease the sum, and we may get a closer sum.\n9. After each iteration of the inner loop, check if the absolute difference between sum and target is less than the absolute difference between closest_sum and target. If it is, update closest_sum to sum.\n10. Return closest_sum after the loop ends.\n# Complexity:\n- Time Complexity: Sorting the array takes O(nlogn) time. The two-pointer approach runs in O(n^2) time. Therefore, the overall time complexity of the solution is O(n^2logn).\n\n- Space Complexity: We are not using any extra space in the solution. Therefore, the space complexity of the solution is O(1).\n\n---\n\n\n# C++\n```\nclass Solution {\npublic:\n int threeSumClosest(vector<int>& nums, int target) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n int closest_sum = nums[0] + nums[1] + nums[2]; // initialize closest sum\n for (int i = 0; i < n - 2; i++) {\n int left = i + 1, right = n - 1;\n while (left < right) { // two-pointer approach\n int sum = nums[i] + nums[left] + nums[right];\n if (sum == target) { // sum equals target, return immediately\n return sum;\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n if (abs(sum - target) < abs(closest_sum - target)) { // update closest sum\n closest_sum = sum;\n }\n }\n }\n return closest_sum;\n }\n};\n\n```\n\n---\n# JAVA\n```\nclass Solution {\n public int threeSumClosest(int[] nums, int target) {\n Arrays.sort(nums);\n int n = nums.length;\n int closest_sum = nums[0] + nums[1] + nums[2]; // initialize closest sum\n for (int i = 0; i < n - 2; i++) {\n int left = i + 1, right = n - 1;\n while (left < right) { // two-pointer approach\n int sum = nums[i] + nums[left] + nums[right];\n if (sum == target) { // sum equals target, return immediately\n return sum;\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n if (Math.abs(sum - target) < Math.abs(closest_sum - target)) { // update closest sum\n closest_sum = sum;\n }\n }\n }\n return closest_sum;\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def threeSumClosest(self, nums, target):\n nums.sort()\n n = len(nums)\n closest_sum = nums[0] + nums[1] + nums[2] # initialize closest sum\n for i in range(n - 2):\n left, right = i + 1, n - 1\n while left < right: # two-pointer approach\n sum = nums[i] + nums[left] + nums[right]\n if sum == target: # sum equals target, return immediately\n return sum\n elif sum < target:\n left += 1\n else:\n right -= 1\n if abs(sum - target) < abs(closest_sum - target): # update closest sum\n closest_sum = sum\n return closest_sum\n\n```\n\n---\n# JavaScript\n```\nvar threeSumClosest = function(nums, target) {\n nums.sort((a, b) => a - b);\n let n = nums.length;\n let closest_sum = nums[0] + nums[1] + nums[2]; // initialize closest sum\n for (let i = 0; i < n - 2; i++) {\n let left = i + 1, right = n - 1;\n while (left < right) { // two-pointer approach\n let sum = nums[i] + nums[left] + nums[right];\n if (sum == target) { // sum equals target, return immediately\n return sum;\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n if (Math.abs(sum - target) < Math.abs(closest_sum - target)) { // update closest sum\n closest_sum = sum;\n }\n }\n }\n return closest_sum;\n};\n\n```
1,564
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
2,613
21
```\nclass Solution {\n public int threeSumClosest(int[] nums, int target) {\n Arrays.sort(nums);\n int n=nums.length;\n int minDiff=Integer.MAX_VALUE;\n int ans=0;\n for(int i=0;i<n-2;i++){\n int low=i+1,high=n-1;\n while(low<high){\n int temp=nums[i]+nums[low]+nums[high];\n if(Math.abs(target-temp)<minDiff){\n ans=temp;\n minDiff=Math.abs(target-temp);\n }\n if(temp==target){\n return target;\n }\n else if(temp>target){\n high--;\n }\n else{\n low++;\n }\n }\n }\n return ans;\n \n } \n}\n```
1,578
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
859
9
This solution runs in around 250ms to 300ms (faster than 80%) . Other two two-pointer solutions tend to be TLE since the new test cases were added. \nIn the 3sum solution the update rule starts with\n```\nk = i+1\nj = len(nums) - 1\n```\nand then increments these:\n```\nif nums[i] + nums[k] + nums[j] < target:\n k+=1\nelse:\n j-=1\n```\nHowever, instead of updating these incrementally we can directly fast-forward them using binary search. i.e. at minimum nums[k] would have to be to flip the if statement is target - num[i] - nums[j]. The same logic can be applied to update j using binary search. \n```\ndef threeSumClosest(self, nums: List[int], target: int) -> int:\n nums.sort()\n \n best = None\n \n # The window is: [i, k, j]\n # Valid range for i:\n for i in range(0, len(nums) - 2):\n # Instead of incrementaly updating the j and k,\n # we can use binary search to find the next viable value\n # for each.\n # We pingpong between updating j and k\n pingpong = 0\n \n # Pick a k (j will be overriden on first pass)\n k = i+1\n j = len(nums)\n\n while j > i + 2:\n if pingpong%2 == 0:\n # Decrease j until sum can be less than target\n targetVal = target - nums[i] - nums[k]\n newj = bisect_left(nums, targetVal, k+1, j-1)\n # There is no possible update to j, can stop\n # searching\n if newj == j:\n break\n j = newj\n pingpong += 1\n else:\n # Increase k until sum can exceed target\n targetVal = target - nums[i] - nums[j]\n k = bisect_left(nums, targetVal, i+1, j-1)\n if nums[k] > targetVal and k > i+1:\n k = k - 1\n pingpong += 1\n\n new = nums[i] + nums[k] + nums[j]\n if best is None or (abs(best - target) > abs(target - new)):\n best = new\n\n if best == target:\n return target\n\n return best
1,581
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
2,224
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the input array nums to enable the two-pointer approach, which helps in efficiently finding the three integers with the closest sum to the target value.\n\nInitialize closestSum and minDiff to large values, as placeholders for the closest sum and minimum difference between sum and target, respectively.\n\nLoop through the array from index 0 to nums.length - 2, as the three-pointer approach requires at least three elements to find a sum.\n\nInside the loop, set up two pointers, left and right, to the elements immediately after the current element and the last element of the array, respectively.\n\nUse a while loop to continuously move the left and right pointers towards each other until they meet or cross each other.\n\nCalculate the current sum by adding the values at the current element, nums[left], and nums[right].\n\nCalculate the absolute difference between the current sum and the target value, and update minDiff and closestSum if the current difference is smaller than the previous minimum difference.\n\nIf the current sum is less than the target, increment the left pointer to consider a larger value.\n\nIf the current sum is greater than the target, decrement the right pointer to consider a smaller value.\n\nIf the current sum is equal to the target, return it as the closest sum.\n\nAfter the loop completes, return the closestSum as the final result, which represents the three integers in the array whose sum is closest to the target value. Note that the returned value may be greater or smaller than the target, depending on the input array and target value. Thus, the caller can check the actual difference between the returned sum and the target value if needed. Also, note that this code assumes that the input array nums has at least three elements. If that\'s not guaranteed, appropriate error handling or input validation should be added. Additionally, the code assumes that the\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```\nimport java.util.*;\n\nclass Solution {\n public int threeSumClosest(int[] nums, int target) {\n Arrays.sort(nums); // Sort the array to enable two-pointer approach\n int closestSum = Integer.MAX_VALUE; // Initialize closest sum to a large value\n int minDiff = Integer.MAX_VALUE; // Initialize minimum difference to a large value\n\n for (int i = 0; i < nums.length - 2; i++) {\n int left = i + 1; // Pointer for the element on the left\n int right = nums.length - 1; // Pointer for the element on the right\n\n while (left < right) {\n int sum = nums[i] + nums[left] + nums[right]; // Calculate the current sum\n\n int diff = Math.abs(sum - target); // Calculate the absolute difference between current sum and target\n if (diff < minDiff) { // Update the minimum difference and closest sum if necessary\n minDiff = diff;\n closestSum = sum;\n }\n\n if (sum < target) {\n left++; // If current sum is less than target, increment the left pointer\n } else if (sum > target) {\n right--; // If current sum is greater than target, decrement the right pointer\n } else {\n return sum; // If current sum is equal to target, return it as the closest sum\n }\n }\n }\n\n return closestSum; // Return the closest sum after traversing the entire array\n }\n}\n\n```
1,584
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
8,574
91
![image]()\n```\nclass Solution {\npublic:\n int threeSumClosest(vector<int>& nums, int target) {\n sort(nums.begin(),nums.end());//I am going to use Two pointer for that i\'m sorting it if you want to use some other approch feel free to do that;\n int n=nums.size();\n\n int sum=nums[0]+nums[1]+nums[2];//Our Intial sum or assuption that intial three values are the closet sum\n for(int i=0;i<n-2;i++){ //n-2 Since we have taken n-1 in our point so no need to go beyond that\n //Implementing Two pointer technique\n int j=i+1;\n int k=n-1;\n while(j<k){\n int temp=nums[i]+nums[j]+nums[k];//Temparory sum for comaprison\n if(abs(temp-target) < abs(sum-target) ) sum=temp;//if we find batter or closer sum then we update the above sum value\n if(temp>target){\n k--; // if value is greater than target one just come one point right to left\n } else if(temp<target){\n j++; //if value is lower than target just come one point left to right \n \n }else return target;// if value already found no need to go for other just return \n }\n \n }\n return sum;\n }\n};\n```Hey Folk I\'m using Two Pointer technique technique if you really want to appreciate and fount it batter*** please Up vote Thank You:)***
1,586
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
483
5
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n^2)\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 threeSumClosest(vector<int>& nums, int target) {\n int min_sum = INT_MAX, ans;\n sort(nums.begin(), nums.end());\n for(int i=0; i<nums.size(); i++) {\n int l = i + 1, r = nums.size() - 1; \n while (l < r) {\n int sum = nums[i] + nums[l] + nums[r];\n if(sum == target) {\n return sum;\n }\n else if(sum < target) {\n if(target - sum < min_sum) {\n min_sum = target - sum;\n ans = sum;\n }\n l++;\n }\n else if(sum > target) {\n if(sum - target < min_sum) {\n min_sum = sum - target;\n ans = sum;\n }\n r--;\n }\n }\n }\n return ans;\n }\n};\n```
1,587
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
2,440
7
# Complexity\n- Time complexity: O(N^2)\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```\nclass Solution {\n public int threeSumClosest(int[] nums, int target) {\n Arrays.sort(nums);\n int minDistance = Integer.MAX_VALUE;\n int closestSum = 0;\n\n for(int i = 0; i < nums.length - 2; i++) {\n int start = i + 1;\n int end = nums.length - 1;\n\n while(start < end) {\n int sum = nums[i] + nums[start] + nums[end];\n int distance = Math.abs(target - sum);\n\n if(sum == target) {\n return sum;\n } \n\n if(distance < minDistance) {\n minDistance = distance;\n closestSum = sum;\n }\n\n if(sum < target) {\n start++;\n } else {\n end--;\n }\n }\n }\n return closestSum;\n }\n}\n```
1,589
3Sum Closest
3sum-closest
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Array,Two Pointers,Sorting
Medium
null
3,114
47
<blockquote>\n<b>Disclaimer:</b> By using any content from this post or thread, you release the author(s) from all liability and warranty of any kind. You are free to use the content freely and as you see fit. Any suggestions for improvement are welcome and greatly appreciated! Happy coding!\n</blockquote>\n\n```swift\nclass Solution {\n func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {\n \n let sorted = nums.sorted()\n let length = sorted.count\n \n var diff: Int = .max\n var result = 0\n \n for i in 0..<length - 2 {\n var n = i + 1, q = length - 1\n while n < q {\n let sum = sorted[i] + sorted[n] + sorted[q]\n \n sum > target ? (q -= 1) : (n += 1)\n \n let value = abs(sum - target)\n \n if value < diff {\n diff = value\n result = sum\n }\n }\n }\n return result\n }\n}\n```\n\n---\n\n<details>\n<summary>\n<img src="" height="24">\n<b>TEST CASES</b>\n</summary>\n\n<pre>\n<b>Result:</b> Executed 1 test, with 0 failures (0 unexpected) in 0.004 (0.006) seconds\n</pre>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n func test() {\n let value = solution.threeSumClosest([-1,2,1,-4], 1)\n XCTAssertEqual(value, 2)\n }\n}\n\nTests.defaultTestSuite.run()\n```\n</details>
1,596
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Hash Table,String,Backtracking
Medium
null
524
5
![image.png]()\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* The logic is so simple, all you need to do is to create map similar to the phone map.\n* and apply multiple neasted loops, and just keep taking characters in sequence. \n* so in case of 23, we will do the following loop \n ```\n for (char c : mp[2])\n for (char d : mp[3])\n ans.push_back(c+d);\n ```\n* And keeping in mind that if we have any 1 we should neglect them\n* ie: 213 should give the same answer as 23\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* Firstly define a static phone map\n* Secondly remove all ones from the digits using this built in method: \n ```\n digits.erase(remove(digits.begin(), digits.end(), \'1\'), digits.end()); // remove 1s from string \n ```\n* now all we need to do is to apply the neasted loops as you can see in intuition, so to do so I used recursive method **backtracking**\n\n## Backtracking (i, digits, s, ans)\n### return type and parameters \n1. Return Type: it returns nothing\n2. Parameter: \n - i: the index of the current digit.\n - digits: the given string of digits. \n - s: this is the formatted string till the current call. \n - ans: this is the vector in which we store all possible combinations.\n### Basecase \n* our basecase is when i is same as the length of the given digits, because all the result strings must be same length as the given digits.\n* so if it happens, we should make sure that our string has at least one character, because in test case 2, he insert empty string, so we should return empty vector not {\'\'}. \n* if this happend just insert s in the result.\n* then return. \n### recursive logic\n* just loop over all characters exist in the map of the current digit, and increment i by 1 in each call and append that character to s\n ```\n for (auto chr : mp[digits[i]])\n backtracking(i + 1, digits, s + chr, ans)\n ```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. O(4^l) where l is the length of the given digits string\n> 4 not 3 because 7 & 9 contains 4 charachters, so there may be a case where we have 9999 or 7777 so it will be 4^4. \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. O(4 * 4^l) = O(4 ^ (l + 1)) which is the matrix for storing all possible combinations. \n# Code\n```\nclass Solution {\n public:\n #define DPSolver ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n\n map<char, vector<char>> mp = {\n {\'2\', {\'a\', \'b\', \'c\'}},\n {\'3\', {\'d\', \'e\', \'f\'}},\n {\'4\', {\'g\', \'h\', \'i\'}},\n {\'5\', {\'j\', \'k\', \'l\'}},\n {\'6\', {\'m\', \'n\', \'o\'}},\n {\'7\', {\'p\', \'q\', \'r\', \'s\'}},\n {\'8\', {\'t\', \'u\', \'v\'}},\n {\'9\', {\'w\', \'x\', \'y\', \'z\'}}};\n\n void backtracking(int i, string digits, string s, vector<string> &ans)\n {\n // base cases\n if (i == digits.length())\n {\n if (s.length())\n ans.push_back(s);\n return;\n }\n\n for (auto chr : mp[digits[i]])\n backtracking(i + 1, digits, s + chr, ans);\n }\n\n vector<string> letterCombinations(string digits)\n {\n DPSolver;\n // remove all ones\n digits.erase(remove(digits.begin(), digits.end(), \'1\'), digits.end());\n vector<string> ans;\n backtracking(0, digits, "", ans);\n return ans;\n }\n\n};\n```
1,618
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Hash Table,String,Backtracking
Medium
null
16,362
92
# Intuition\nGiven a string containing digits from 2-9 inclusive, we need to return all possible letter combinations that the number could represent, just like on a telephone\'s buttons. To accomplish this, we present two different approaches:\n\n1. **Backtracking Approach**: This approach leverages recursion to explore all possible combinations. We create a recursive function that takes the current combination and the next digits to explore. For each digit, we iterate through its corresponding letters and recursively explore the remaining digits. We append the combination when no more digits are left to explore.\n\n2. **Iterative Approach**: This approach builds the combinations iteratively without using recursion. We start with an empty combination and iteratively add letters for each digit in the input string. For each existing combination, we append each corresponding letter for the current digit, building new combinations.\n\n**Differences**:\n- The backtracking approach relies on recursion to explore all possible combinations, whereas the iterative approach builds combinations step by step using loops.\n- Both approaches have similar time complexity, but the iterative approach might save some function call overhead, leading to more efficient execution in some cases.\n\nDetailed explanations of both approaches, along with their corresponding code, are provided below. By presenting both methods, we offer a comprehensive view of how to tackle this problem, allowing for flexibility and understanding of different programming paradigms.\n\n\n\n# Approach - Backtracking\n1. **Initialize a Mapping**: Create a dictionary that maps each digit from 2 to 9 to their corresponding letters on a telephone\'s buttons. For example, the digit \'2\' maps to "abc," \'3\' maps to "def," and so on.\n\n2. **Base Case**: Check if the input string `digits` is empty. If it is, return an empty list, as there are no combinations to generate.\n\n3. **Recursive Backtracking**:\n - **Define Recursive Function**: Create a recursive function, `backtrack`, that will be used to explore all possible combinations. It takes two parameters: `combination`, which holds the current combination of letters, and `next_digits`, which holds the remaining digits to be explored.\n - **Termination Condition**: If `next_digits` is empty, it means that all digits have been processed, so append the current `combination` to the result.\n - **Exploration**: If there are more digits to explore, take the first digit from `next_digits` and iterate over its corresponding letters in the mapping. For each letter, concatenate it to the current combination and recursively call the `backtrack` function with the new combination and the remaining digits.\n - **Example**: If the input is "23", the first recursive call explores all combinations starting with \'a\', \'b\', and \'c\' (from \'2\'), and the next level of recursive calls explores combinations starting with \'d\', \'e\', \'f\' (from \'3\'), building combinations like "ad," "ae," "af," "bd," "be," etc.\n\n4. **Result**: Once the recursive exploration is complete, return the collected combinations as the final result. By using recursion, we ensure that all possible combinations are explored, and the result includes all valid letter combinations that the input digits can represent.\n\n# Complexity\n- Time complexity: \\( O(4^n) \\), where \\( n \\) is the length of the input string. In the worst case, each digit can represent 4 letters, so there will be 4 recursive calls for each digit.\n- Space complexity: \\( O(n) \\), where \\( n \\) is the length of the input string. This accounts for the recursion stack space.\n\n# Code - Backtracking\n``` Python []\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n if not digits:\n return []\n\n phone_map = {\n \'2\': \'abc\',\n \'3\': \'def\',\n \'4\': \'ghi\',\n \'5\': \'jkl\',\n \'6\': \'mno\',\n \'7\': \'pqrs\',\n \'8\': \'tuv\',\n \'9\': \'wxyz\'\n }\n\n def backtrack(combination, next_digits):\n if len(next_digits) == 0:\n output.append(combination)\n else:\n for letter in phone_map[next_digits[0]]:\n backtrack(combination + letter, next_digits[1:])\n\n output = []\n backtrack("", digits)\n return output\n```\n``` C++ []\nclass Solution {\npublic:\n std::vector<std::string> letterCombinations(std::string digits) {\n if (digits.empty()) return {};\n\n std::string phone_map[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n std::vector<std::string> output;\n backtrack("", digits, phone_map, output);\n return output;\n }\n\nprivate:\n void backtrack(std::string combination, std::string next_digits, std::string phone_map[], std::vector<std::string>& output) {\n if (next_digits.empty()) {\n output.push_back(combination);\n } else {\n std::string letters = phone_map[next_digits[0] - \'2\'];\n for (char letter : letters) {\n backtrack(combination + letter, next_digits.substr(1), phone_map, output);\n }\n }\n }\n};\n```\n``` Java []\nclass Solution {\n public List<String> letterCombinations(String digits) {\n if (digits.isEmpty()) return Collections.emptyList();\n\n String[] phone_map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n List<String> output = new ArrayList<>();\n backtrack("", digits, phone_map, output);\n return output;\n }\n\n private void backtrack(String combination, String next_digits, String[] phone_map, List<String> output) {\n if (next_digits.isEmpty()) {\n output.add(combination);\n } else {\n String letters = phone_map[next_digits.charAt(0) - \'2\'];\n for (char letter : letters.toCharArray()) {\n backtrack(combination + letter, next_digits.substring(1), phone_map, output);\n }\n }\n }\n}\n```\n``` JavaSxript []\n/**\n * @param {string} digits\n * @return {string[]}\n */\nvar letterCombinations = function(digits) {\n if (digits.length === 0) return [];\n\n const phone_map = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];\n const output = [];\n backtrack("", digits, phone_map, output);\n return output;\n\n function backtrack(combination, next_digits, phone_map, output) {\n if (next_digits.length === 0) {\n output.push(combination);\n } else {\n const letters = phone_map[next_digits[0] - \'2\'];\n for (const letter of letters) {\n backtrack(combination + letter, next_digits.slice(1), phone_map, output);\n }\n }\n }\n};\n```\n``` C# []\npublic class Solution {\n public IList<string> LetterCombinations(string digits) {\n if (string.IsNullOrEmpty(digits)) return new List<string>();\n\n string[] phone_map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n List<string> output = new List<string>();\n Backtrack("", digits, phone_map, output);\n return output;\n }\n\n private void Backtrack(string combination, string next_digits, string[] phone_map, List<string> output) {\n if (next_digits.Length == 0) {\n output.Add(combination);\n } else {\n string letters = phone_map[next_digits[0] - \'2\'];\n foreach (char letter in letters) {\n Backtrack(combination + letter, next_digits.Substring(1), phone_map, output);\n }\n }\n }\n}\n```\n``` Go []\nfunc letterCombinations(digits string) []string {\n\tif digits == "" {\n\t\treturn []string{}\n\t}\n\n\tphoneMap := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}\n\tvar output []string\n\n\tvar backtrack func(combination string, nextDigits string)\n\tbacktrack = func(combination string, nextDigits string) {\n\t\tif nextDigits == "" {\n\t\t\toutput = append(output, combination)\n\t\t} else {\n\t\t\tletters := phoneMap[nextDigits[0]-\'2\']\n\t\t\tfor _, letter := range letters {\n\t\t\t\tbacktrack(combination+string(letter), nextDigits[1:])\n\t\t\t}\n\t\t}\n\t}\n\n\tbacktrack("", digits)\n\treturn output\n}\n```\n``` Rust []\nimpl Solution {\n pub fn letter_combinations(digits: String) -> Vec<String> {\n if digits.is_empty() {\n return vec![];\n }\n\n let phone_map = vec!["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];\n let mut output = Vec::new();\n\n fn backtrack(combination: String, next_digits: &str, phone_map: &Vec<&str>, output: &mut Vec<String>) {\n if next_digits.is_empty() {\n output.push(combination);\n } else {\n let letters = phone_map[next_digits.chars().nth(0).unwrap() as usize - \'2\' as usize];\n for letter in letters.chars() {\n let new_combination = combination.clone() + &letter.to_string();\n backtrack(new_combination, &next_digits[1..], phone_map, output);\n }\n }\n }\n\n backtrack(String::new(), &digits, &phone_map, &mut output);\n output\n }\n}\n```\nThis code can handle any input string containing digits from 2 to 9 and will return the possible letter combinations in any order. The function `backtrack` is used to handle the recursive exploration of combinations, and `phone_map` contains the mapping between digits and letters.\n\n## Performance - Backtracking\n\n| Language | Runtime (ms) | Beats (%) | Memory (MB) |\n|-------------|--------------|-----------|-------------|\n| C++ | 0 | 100.00 | 6.4 |\n| Go | 0 | 100.00 | 2.0 |\n| Rust | 1 | 82.50 | 2.1 |\n| Java | 5 | 50.30 | 41.6 |\n| Swift | 2 | 82.38 | 14.0 |\n| Python3 | 34 | 96.91 | 16.3 |\n| TypeScript | 49 | 96.36 | 44.3 |\n| JavaScript | 58 | 55.17 | 42.2 |\n| Ruby | 58 | 97.98 | 211.1 |\n| C# | 136 | 89.14 | 43.9 |\n\n# Video Iterative\n\n\n# Approach - Iterative\n1. **Initialize a Mapping**: Create a dictionary that maps each digit from 2 to 9 to their corresponding letters on a telephone\'s buttons.\n2. **Base Case**: If the input string `digits` is empty, return an empty list.\n3. **Iteratively Build Combinations**: Start with an empty combination in a list and iteratively build the combinations by processing each digit in the input string.\n - For each existing combination, append each corresponding letter for the current digit, building new combinations.\n4. **Result**: Return the generated combinations as the final result.\n\n# Complexity\n- Time complexity: \\( O(4^n) \\), where \\( n \\) is the length of the input string. In the worst case, each digit can represent 4 letters.\n- Space complexity: \\( O(n) \\), where \\( n \\) is the length of the input string.\n\n# Code - Iterative\n``` Python []\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n if not digits:\n return []\n\n phone_map = {\n \'2\': \'abc\',\n \'3\': \'def\',\n \'4\': \'ghi\',\n \'5\': \'jkl\',\n \'6\': \'mno\',\n \'7\': \'pqrs\',\n \'8\': \'tuv\',\n \'9\': \'wxyz\'\n }\n combinations = [""]\n\n for digit in digits:\n new_combinations = []\n for combination in combinations:\n for letter in phone_map[digit]:\n new_combinations.append(combination + letter)\n combinations = new_combinations\n\n return combinations\n```\n``` JavaScript []\nfunction letterCombinations(digits) {\n if (!digits) {\n return [];\n }\n\n const phoneMap = {\n \'2\': \'abc\',\n \'3\': \'def\',\n \'4\': \'ghi\',\n \'5\': \'jkl\',\n \'6\': \'mno\',\n \'7\': \'pqrs\',\n \'8\': \'tuv\',\n \'9\': \'wxyz\'\n };\n\n let combinations = [\'\'];\n\n for (const digit of digits) {\n const newCombinations = [];\n for (const combination of combinations) {\n for (const letter of phoneMap[digit]) {\n newCombinations.push(combination + letter);\n }\n }\n combinations = newCombinations;\n }\n\n return combinations;\n}\n```\n``` C++ []\nclass Solution {\npublic:\n std::vector<std::string> letterCombinations(std::string digits) {\n if (digits.empty()) return {};\n\n std::string phone_map[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n std::vector<std::string> combinations = {""};\n\n for (char digit : digits) {\n std::vector<std::string> new_combinations;\n for (std::string combination : combinations) {\n for (char letter : phone_map[digit - \'2\']) {\n new_combinations.push_back(combination + letter);\n }\n }\n combinations = new_combinations;\n }\n\n return combinations;\n }\n};\n```\n``` Go []\nfunc letterCombinations(digits string) []string {\n if digits == "" {\n return []string{}\n }\n\n phoneMap := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}\n combinations := []string{""}\n\n for _, digit := range digits {\n newCombinations := []string{}\n for _, combination := range combinations {\n for _, letter := range phoneMap[digit-\'2\'] {\n newCombinations = append(newCombinations, combination+string(letter))\n }\n }\n combinations = newCombinations\n }\n\n return combinations\n}\n```\n\n\nIf you find the solution understandable and helpful, don\'t hesitate to give it an upvote. Engaging with the code across different languages might just lead you to discover new techniques and preferences! Happy coding! \uD83D\uDE80\uD83E\uDD80\uD83D\uDCDE\n
1,619
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Hash Table,String,Backtracking
Medium
null
2,322
49
# Intuition\nMy initial thoughts on solving this problem involve using a recursive approach to generate all possible letter combinations for a given set of digits. We can associate each digit with a set of letters, similar to a phone\'s keypad, and then combine these letters to form all possible combinations\n\n# Approach\nI have implemented a solution using Java. Here\'s a breakdown of the approach:\n\nWe create a Map called digitToLetters to store the mapping of each digit to the corresponding letters.\n\nWe initialize an empty List called resultList to store the final letter combinations.\n\nIn the letterCombinations method, we first check if the input digits is null or empty. If it is, we return the empty resultList.\n\nWe populate the digitToLetters map with the mappings for digits 2 to 9, where each digit is associated with a string of letters.\n\nWe call the generateCombinations method to start the recursive process of generating letter combinations.\n\nInside the generateCombinations method, we check if we have processed all the digits (i.e., currentIndex equals the length of digits). If so, we add the current combination to the resultList.\n\nIf we haven\'t processed all the digits yet, we retrieve the letters associated with the current digit from the digitToLetters map.\n\nWe iterate through the available letters, appending each letter to the currentCombination, recursively generating combinations for the next digit, and then removing the last character to backtrack and explore other possibilities.\n\nTime complexity: The time complexity is O(4^n * n), where n is the length of the input string digits. In the worst case, each digit can represent up to four letters, and there are n digits. The recursive backtracking explores all possible combinations.\n\nSpace complexity: The space complexity is O(n), where n is the length of the input string digits. This is the space required for the recursive call stack. Additionally, the space used for the resultList is considered in the space complexity.\n\n\n\n# Code\n```\nclass Solution {\n private Map<Character, String> digitToLetters = new HashMap<>();\n private List<String> resultList = new ArrayList<>();\n\n public List<String> letterCombinations(String digits) {\n if (digits == null || digits.length() == 0) {\n return resultList;\n }\n\n digitToLetters.put(\'2\', "abc");\n digitToLetters.put(\'3\', "def");\n digitToLetters.put(\'4\', "ghi");\n digitToLetters.put(\'5\', "jkl");\n digitToLetters.put(\'6\', "mno");\n digitToLetters.put(\'7\', "pqrs");\n digitToLetters.put(\'8\', "tuv");\n digitToLetters.put(\'9\', "wxyz");\n\n generateCombinations(digits, 0, new StringBuilder());\n\n return resultList;\n\n\n }\n\n\n private void generateCombinations(String digits, int currentIndex, StringBuilder currentCombination) {\n if (currentIndex == digits.length()) {\n resultList.add(currentCombination.toString());\n return;\n }\n\n char currentDigit = digits.charAt(currentIndex);\n String letterOptions = digitToLetters.get(currentDigit);\n\n if (letterOptions != null) {\n for (int i = 0; i < letterOptions.length(); i++) {\n char letter = letterOptions.charAt(i);\n currentCombination.append(letter);\n generateCombinations(digits, currentIndex + 1, currentCombination);\n currentCombination.deleteCharAt(currentCombination.length() - 1);\n }\n }\n }\n}\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]()\n
1,620