title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
22,457
170
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\nVisit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: \n\n**Solution:**\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n # Creating Dictionary for Lookup\n num_map = {\n 1: "I",\n 5: "V", 4: "IV",\n 10: "X", 9: "IX",\n 50: "L", 40: "XL",\n 100: "C", 90: "XC",\n 500: "D", 400: "CD",\n 1000: "M", 900: "CM",\n }\n \n # Result Variable\n r = \'\'\n \n \n for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:\n # If n in list then add the roman value to result variable\n while n <= num:\n r += num_map[n]\n num-=n\n return r\n```\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.**
1,109
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
14,699
50
# Intuition:\nThe given problem is about converting an integer into a Roman numeral. To do this, we can create arrays that represent the Roman numeral symbols for each place value (ones, tens, hundreds, thousands). Then, we can divide the given number into its respective place values and concatenate the corresponding Roman numeral symbols.\n\n# Approach:\n1. Create four arrays: `ones`, `tens`, `hrns`, and `ths`, representing the Roman numeral symbols for ones, tens, hundreds, and thousands respectively. Each array contains the symbols for the numbers from 0 to 9 in their respective place value.\n2. Divide the given number `num` into its respective place values:\n - `thousands = num / 1000`\n - `hundreds = (num % 1000) / 100`\n - `tens = (num % 100) / 10`\n - `ones = num % 10`\n3. Concatenate the Roman numeral symbols based on the place values:\n - `ths[num/1000]` represents the Roman numeral for thousands place.\n - `hrns[(num%1000)/100]` represents the Roman numeral for hundreds place.\n - `tens[(num%100)/10]` represents the Roman numeral for tens place.\n - `ones[num%10]` represents the Roman numeral for ones place.\n4. Return the concatenation of the Roman numeral symbols obtained from step 3.\n\n# Complexity:\n- Time complexity: O(1) because the number of digits in the given number is constant (up to 4 digits for the given range).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) because the arrays storing the Roman numeral values have fixed sizes.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n# C++\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n string ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};\n string tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};\n string hrns[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};\n string ths[]={"","M","MM","MMM"};\n \n return ths[num/1000] + hrns[(num%1000)/100] + tens[(num%100)/10] + ones[num%10];\n }\n};\n```\n\n---\n# JAVA\n```\nclass Solution {\n public String intToRoman(int num) {\n String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};\n String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};\n String[] hrns = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};\n String[] ths = {"", "M", "MM", "MMM"};\n\n return ths[num / 1000] + hrns[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];\n }\n}\n\n```\n\n---\n# JavaScript\n```\nvar intToRoman = function(num) {\n const ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];\n const tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];\n const hrns = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];\n const ths = ["", "M", "MM", "MMM"];\n return ths[Math.floor(num / 1000)] + hrns[Math.floor((num % 1000) / 100)] + tens[Math.floor((num % 100) / 10)] + ones[num % 10];\n};\n```\n---\n# Python\n```\nclass Solution:\n def intToRoman(self, num):\n ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]\n tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]\n hrns = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]\n ths = ["", "M", "MM", "MMM"]\n\n return ths[num / 1000] + hrns[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10]\n\n```
1,118
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
1,447
5
```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n symbolMap = {\n 1 : "I", \n 5 : \'V\', \n 10 : "X", \n 50 : "L", \n 100 : "C", \n 500 : "D", \n 1000 : "M"\n }\n \n res = [] \n while num >= 1000: \n res.append(symbolMap[1000])\n num -= 1000 \n \n while num >= 900: \n res.append(symbolMap[100])\n res.append(symbolMap[1000])\n num -= 900 \n \n while num >= 500: \n res.append(symbolMap[500])\n num -= 500\n \n while num >= 400: \n res.append(symbolMap[100])\n res.append(symbolMap[500])\n num -= 400 \n \n while num >= 100: \n res.append(symbolMap[100])\n num -= 100 \n \n while num >= 90: \n res.append(symbolMap[10])\n res.append(symbolMap[100])\n num -= 90 \n \n while num >= 50: \n res.append(symbolMap[50])\n num -= 50 \n \n while num >= 40: \n res.append(symbolMap[10])\n res.append(symbolMap[50])\n num -= 40 \n \n while num >= 10: \n res.append(symbolMap[10])\n num -= 10\n \n while num >= 9: \n res.append(symbolMap[1])\n res.append(symbolMap[10])\n num -= 400 \n \n while num >= 5:\n res.append(symbolMap[5])\n num -= 5 \n \n while num >= 4: \n res.append(symbolMap[1])\n res.append(symbolMap[5])\n num -= 400 \n \n while num >= 1: \n res.append(symbolMap[1])\n num -= 1 \n \n return "".join(res)\n```
1,124
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
5,904
37
\n\n# Python Solution\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n M=["","M","MM","MMM"]\n C=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"]\n X=["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"]\n I=["","I","II","III","IV","V","VI","VII","VIII","IX"]\n return M[num//1000]+C[num%1000//100]+X[num%1000%100//10]+I[num%1000%100%10]\n```\n# please upvote me it would encourage me alot\n
1,141
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
18,397
152
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nJust like Roman to Integer, this problem is most easily solved using a **lookup table** for the conversion between digit and numeral. In this case, we can easily deal with the values in descending order and insert the appropriate numeral (or numerals) as many times as we can while reducing the our target number (**N**) by the same amount.\n\nOnce **N** runs out, we can **return ans**.\n\n---\n\n#### ***Implementation:***\n\nJava\'s **StringBuilder** can take care of repeated string concatenations without some of the overhead of making string copies.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **124ms / 43.5MB** (beats 100% / 100%).\n```javascript\nconst val = [1000,900,500,400,100,90,50,40,10,9,5,4,1]\nconst rom = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]\n\nvar intToRoman = function(N) {\n let ans = ""\n for (let i = 0; N; i++)\n while (N >= val[i]) ans += rom[i], N -= val[i]\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **40ms / 14.1MB** (beats 95% / 86%).\n```python\nval = [1000,900,500,400,100,90,50,40,10,9,5,4,1]\nrom = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]\n\nclass Solution:\n def intToRoman(self, N: int) -> str:\n ans = ""\n for i in range(13):\n while N >= val[i]:\n ans += rom[i]\n N -= val[i]\n return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **3ms / 38.1MB** (beats 100% / 95%).\n```java\nclass Solution {\n final static int[] val = {1000,900,500,400,100,90,50,40,10,9,5,4,1};\n final static String[] rom = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n\n public String intToRoman(int N) {\n StringBuilder ans = new StringBuilder();\n for (int i = 0; N > 0; i++)\n while (N >= val[i]) {\n ans.append(rom[i]);\n N -= val[i];\n }\n return ans.toString();\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 5.8MB** (beats 100% / 98%).\n```c++\nclass Solution {\npublic:\n const int val[13] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};\n const string rom[13] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n\n string intToRoman(int N) {\n string ans = "";\n for (int i = 0; N; i++)\n while (N >= val[i]) ans += rom[i], N -= val[i];\n return ans;\n }\n};\n```
1,143
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
2,279
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![image.png]()\n\n# Code\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n x = \'\'\n while num!=0:\n if num>= 1000:\n x+=\'M\'\n num-=1000\n elif num>= 900:\n x+=\'CM\'\n num-=900\n elif num>= 500:\n x+=\'D\'\n num-= 500\n elif num>= 400: \n x+=\'CD\' \n num-= 400\n elif num>= 100:\n x+=\'C\'\n num-=100\n elif num>= 90:\n x+=\'XC\' \n num-=90\n elif num>= 50:\n x+=\'L\' \n num-=50\n elif num>= 40:\n x+=\'XL\' \n num-=40\n elif num>= 10:\n x+=\'X\' \n num-=10\n elif num>= 9:\n x+=\'IX\' \n num-=9\n elif num>= 5:\n x+=\'V\' \n num-=5\n elif num>= 4:\n x+=\'IV\' \n num-=4\n else:\n x+=\'I\'\n num-=1\n return x\n```
1,153
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
1,054
10
```\nclass Solution:\n def intToRoman(self, num: int) -> str: \n\n mils = ["", "M", "MM", "MMM"]\n\n cens = [ "", "C", "CC", "CCC", "CD",\n "D", "DC", "DCC", "DCCC", "CM"]\n\n decs = [ "", "X", "XX", "XXX", "XL",\n "L", "LX", "LXX", "LXXX", "XC"]\n\n unes = [ "", "I", "II", "III", "IV",\n "V", "VI", "VII", "VIII", "IX"] # EX: num = 2579\n\n m, num = divmod(num,1000) # m = 2 num = 579\n c, num = divmod(num,100 ) # m = 5 num = 79\n d, u = divmod(num,10 ) # m = 7 u = 9\n\n return mils[m]+cens[c]+decs[d]+unes[u] # mils[2]+cens[5]+decs[7]+unes[9] = MM + D + LXX + IX = MMDLXXIX \n```\n[](http://)
1,162
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
44,076
262
\n def intToRoman1(self, num):\n values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ]\n numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ]\n res, i = "", 0\n while num:\n res += (num//values[i]) * numerals[i]\n num %= values[i]\n i += 1\n return res\n \n def intToRoman(self, num):\n values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ]\n numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ]\n res = ""\n for i, v in enumerate(values):\n res += (num//v) * numerals[i]\n num %= v\n return res
1,177
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
1,123
6
# Code\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n roman_mapping = {\n 1000: \'M\',\n 900: \'CM\',\n 500: \'D\',\n 400: \'CD\',\n 100: \'C\',\n 90: \'XC\',\n 50: \'L\',\n 40: \'XL\',\n 10: \'X\',\n 9: \'IX\',\n 5: \'V\',\n 4: \'IV\',\n 1: \'I\'\n }\n result = ""\n for value, symbol in roman_mapping.items():\n while num >= value:\n result += symbol\n num -= value\n return result\n\n```
1,181
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
1,104
10
**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n**** \n**Python.** This [**solution**]() employs a repetition of Roman digits. It demonstrated **47 ms runtime (96.77%)** and used **13.9 MB memory (35.57%)**. Time complexity is contstant: **O(1)**. Space complexity is constant: **O(1)**.\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n \n\t\t# Starting from Python 3.7, dictionary order is guaranteed \n\t\t# to be insertion order\n num_to_roman = { 1000 : "M", 900 : "CM", 500 : "D", 400 : "CD",\n 100 : "C", 90 : "XC", 50 : "L", 40 : "XL",\n 10 : "X", 9 : "IX", 5 : "V", 4 : "IV",\n 1 : "I" }\n roman: str = ""\n\n # The idea is to repeat each of Roman digits as many times\n # as needed to cover the decimal representation.\n for i, r in num_to_roman.items():\n roman += r * (num // i)\n num %= i\n else:\n return roman\n```\n**** \n**Rust.** This [**solution**]() employs a brute force digit substitution. It demonstrated **0 ms runtime (100.00%)** and used **2.0 MB memory (94.20%)**. Time complexity is constant: **O(1)**. Space complexity is constant: **O(1)**.\n```\nconst ONES : [&str;10] = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];\nconst TENS : [&str;10] = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];\nconst CENT : [&str;10] = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];\nconst MILS : [&str;4] = ["", "M", "MM", "MMM"];\n\nimpl Solution \n{\n pub fn int_to_roman(num: i32) -> String \n {\n // Given that the number of outcomes is small, a brute force\n\t\t// substituion for each power of ten is a viable solution...\n\t\tformat!("{}{}{}{}", MILS[(num / 1000 % 10) as usize],\n CENT[(num / 100 % 10) as usize],\n TENS[(num / 10 % 10) as usize],\n ONES[(num % 10) as usize])\n }\n}\n```\n**** \n**\u0421++.** This [**solution**]() employs an iterative build-up of a Roman number. It demonstrated **0 ms runtime (100.0%)** and used **6.1 MB memory (47.60%)**. Time complexity is constant: **O(1)**. Space complexity is constant: **O(1)**.\n```\nclass Solution \n{\n const int intgr[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n const string roman[13] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n\npublic:\n string intToRoman(int num)\n {\n string rom = "";\n\t\t\n for (int i = 0; num > 0; i++)\n\t\t // each digit is repeated as many times as needed to \n\t\t\t// completely cover the decimal representation \n while (num >= intgr[i]) rom += roman[i], num -= intgr[i];\n return rom;\n }\n};\n```\n
1,184
Integer to Roman
integer-to-roman
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 an integer, convert it to a roman numeral.
Hash Table,Math,String
Medium
null
4,802
18
```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n i=1\n dic={1:\'I\',5:\'V\',10:\'X\',50:\'L\',100:\'C\',500:\'D\',1000:\'M\'}\n s=""\n while num!=0:\n y=num%pow(10,i)//pow(10,i-1)\n if y==5:\n s=dic[y*pow(10,i-1)]+s\n elif y==1:\n s=dic[y*pow(10,i-1)]+s\n elif y==4:\n s=dic[1*pow(10,i-1)]+dic[5*pow(10,i-1)]+s\n elif y==9:\n s=dic[1*pow(10,i-1)]+dic[1*pow(10,i)]+s\n elif y<4:\n s=dic[pow(10,i-1)]*y+s\n elif y>5 and y<9:\n y-=5\n s=dic[5*pow(10,i-1)]+dic[pow(10,i-1)]*y+s\n num=num//pow(10,i)\n num*=pow(10,i)\n i+=1\n return s\n```
1,193
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.
199,202
1,369
**Certainly! Let\'s break down the code and provide a clear intuition and explanation, using the examples "IX" and "XI" to demonstrate its functionality.**\n\n# Intuition:\nThe key intuition lies in the fact that in Roman numerals, when a smaller value appears before a larger value, it represents subtraction, while when a smaller value appears after or equal to a larger value, it represents addition.\n\n# Explanation:\n\n1. The unordered map `m` is created and initialized with mappings between Roman numeral characters and their corresponding integer values. For example, \'I\' is mapped to 1, \'V\' to 5, \'X\' to 10, and so on.\n2. The variable `ans` is initialized to 0. This variable will accumulate the final integer value of the Roman numeral string.\n3. The for loop iterates over each character in the input string `s`.\n **For the example "IX":**\n \n - When `i` is 0, the current character `s[i]` is \'I\'. Since there is a next character (\'X\'), and the value of \'I\' (1) is less than the value of \'X\' (10), the condition `m[s[i]] < m[s[i+1]]` is true. In this case, we subtract the value of the current character from `ans`.\n \n `ans -= m[s[i]];`\n `ans -= m[\'I\'];`\n `ans -= 1;`\n `ans` becomes -1.\n \n - When `i` is 1, the current character `s[i]` is \'X\'. This is the last character in the string, so there is no next character to compare. Since there is no next character, we don\'t need to evaluate the condition. In this case, we add the value of the current character to `ans`.\n \n `ans += m[s[i]];`\n `ans += m[\'X\'];`\n `ans += 10;`\n `ans` becomes 9.\n \n **For the example "XI":**\n \n - When `i` is 0, the current character `s[i]` is \'X\'. Since there is a next character (\'I\'), and the value of \'X\' (10) is greater than the value of \'I\' (1), the condition `m[s[i]] < m[s[i+1]]` is false. In this case, we add the value of the current character to `ans`.\n \n `ans += m[s[i]];`\n `ans += m[\'X\'];`\n `ans += 10;`\n `ans` becomes 10.\n \n - When `i` is 1, the current character `s[i]` is \'I\'. This is the last character in the string, so there is no next character to compare. Since there is no next character, we don\'t need to evaluate the condition. In this case, we add the value of the current character to `ans`.\n \n `ans += m[s[i]];`\n `ans += m[\'I\'];`\n `ans += 1;`\n `ans` becomes 11.\n\n4. After the for loop, the accumulated value in `ans` represents the integer conversion of the Roman numeral string, and it is returned as the result.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> m;\n \n m[\'I\'] = 1;\n m[\'V\'] = 5;\n m[\'X\'] = 10;\n m[\'L\'] = 50;\n m[\'C\'] = 100;\n m[\'D\'] = 500;\n m[\'M\'] = 1000;\n \n int ans = 0;\n \n for(int i = 0; i < s.length(); i++){\n if(m[s[i]] < m[s[i+1]]){\n ans -= m[s[i]];\n }\n else{\n ans += m[s[i]];\n }\n }\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int romanToInt(String s) {\n Map<Character, Integer> m = new HashMap<>();\n \n m.put(\'I\', 1);\n m.put(\'V\', 5);\n m.put(\'X\', 10);\n m.put(\'L\', 50);\n m.put(\'C\', 100);\n m.put(\'D\', 500);\n m.put(\'M\', 1000);\n \n int ans = 0;\n \n for (int i = 0; i < s.length(); i++) {\n if (i < s.length() - 1 && m.get(s.charAt(i)) < m.get(s.charAt(i + 1))) {\n ans -= m.get(s.charAt(i));\n } else {\n ans += m.get(s.charAt(i));\n }\n }\n \n return ans;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n m = {\n \'I\': 1,\n \'V\': 5,\n \'X\': 10,\n \'L\': 50,\n \'C\': 100,\n \'D\': 500,\n \'M\': 1000\n }\n \n ans = 0\n \n for i in range(len(s)):\n if i < len(s) - 1 and m[s[i]] < m[s[i+1]]:\n ans -= m[s[i]]\n else:\n ans += m[s[i]]\n \n return ans\n```\n![CUTE_CAT.png]()\n\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\n1. [Two Sum]()\n2. [Roman to Integer]()\n3. [Palindrome Number]()\n4. [Maximum Subarray]()\n5. [Remove Element]()\n6. [Contains Duplicate]()\n7. [Add Two Numbers]()\n8. [Majority Element]()\n9. [Remove Duplicates from Sorted Array]()\n10. **Practice them in a row for better understanding and please Upvote for more questions.**\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\n\n
1,200
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.
64,700
323
\n# Hash Table in python\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}\n number=0\n for i in range(len(s)-1):\n if roman[s[i]] < roman[s[(i+1)]]:\n number-=roman[s[i]]\n else:\n number+=roman[s[i]]\n return number+roman[s[-1]]\n\n\n```\n# please upvote me it would encourage me alot\n
1,202
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.
165,006
1,920
The Romans would most likely be angered by how it butchers their numeric system. Sorry guys.\n\n```Python\nclass Solution:\n def romanToInt(self, s: str) -> int:\n translations = {\n "I": 1,\n "V": 5,\n "X": 10,\n "L": 50,\n "C": 100,\n "D": 500,\n "M": 1000\n }\n number = 0\n s = s.replace("IV", "IIII").replace("IX", "VIIII")\n s = s.replace("XL", "XXXX").replace("XC", "LXXXX")\n s = s.replace("CD", "CCCC").replace("CM", "DCCCC")\n for char in s:\n number += translations[char]\n return number\n```
1,204
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.
115,492
402
Code:\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman_to_integer = {\n \'I\': 1,\n \'V\': 5,\n \'X\': 10,\n \'L\': 50,\n \'C\': 100,\n \'D\': 500,\n \'M\': 1000,\n }\n s = s.replace("IV", "IIII").replace("IX", "VIIII").replace("XL", "XXXX").replace("XC", "LXXXX").replace("CD", "CCCC").replace("CM", "DCCCC")\n return sum(map(lambda x: roman_to_integer[x], s))\n```\n**Time Complexity**: `O(n)`\n**Space Complexity**: `O(1)`\n<br/>\n
1,210
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,167
12
\n\n<b>Method 1:</b>\nThis solution takes the approach incorporating the general logic of roman numerals into the algorithm. We first create a dictionary that maps each roman numeral to the corresponding integer. We also create a total variable set to 0.\n\nWe then loop over each numeral and check if the one <i>after</i> it is bigger or smaller. If it\'s bigger, we can just add it to our total. If it\'s smaller, that means we have to <i>subtract</i> it from our total instead.\n\nThe loop stops at the second to last numeral and returns the total + the last numeral (since the last numeral always has to be added)\n\n```\nclass Solution(object):\n def romanToInt(self, s):\n roman = {\n "I": 1,\n "V": 5,\n "X": 10,\n "L": 50,\n "C": 100,\n "D": 500,\n "M": 1000\n }\n total = 0\n for i in range(len(s) - 1):\n if roman[s[i]] < roman[s[i+1]]:\n total -= roman[s[i]]\n else:\n total += roman[s[i]]\n return total + roman[s[-1]]\n```\n\n<b>Method 2:</b>\nThis solution takes the approach of saying "The logic of roman numerals is too complicated. Let\'s make it easier by rewriting the numeral so that we only have to <i>add</i> and not worry about subtraction.\n\nIt starts off the same way by creating a dictionary and a total variable. It then performs substring replacement for each of the 6 possible cases that subtraction can be used and replaces it with a version that can just be added together. For example, IV is converted to IIII, so that all the digits can be added up to 4. Then we just loop through the string and add up the total.\n```\n roman = {\n "I": 1,\n "V": 5,\n "X": 10,\n "L": 50,\n "C": 100,\n "D": 500,\n "M": 1000\n }\n total = 0\n s = s.replace("IV", "IIII").replace("IX", "VIIII")\n s = s.replace("XL", "XXXX").replace("XC", "LXXXX")\n s = s.replace("CD", "CCCC").replace("CM", "DCCCC")\n for symbol in s:\n total += roman[symbol]\n return total\n```
1,217
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.
5,313
25
# \u2705Do upvote if you like the solution and explanation please \uD83D\uDE80\n\n# \u2705Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this code is to iterate through the Roman numeral string from right to left, converting each symbol to its corresponding integer value. If the current symbol has a smaller value than the symbol to its right, we subtract its value from the result; otherwise, we add its value to the result. By processing the string from right to left, we can handle cases where subtraction is required (e.g., IV for 4) effectively.\n\n---\n\n# \u2705Approach for code \n<!-- Describe your approach to solving the problem. -->\n1. Create an unordered map (romanValues) to store the integer values corresponding to each Roman numeral symbol (\'I\', \'V\', \'X\', \'L\', \'C\', \'D\', \'M\').\n\n2. Initialize a variable result to 0 to store the accumulated integer value.\n\n3. Iterate through the input string s from right to left (starting from the last character).\n\n4. For each character at index i, get its integer value (currValue) from the romanValues map.\n\n5. Check if the current symbol has a smaller value than the symbol to its right (i.e., currValue < romanValues[s[i + 1]]) using the condition i < s.length() - 1. If true, subtract currValue from the result; otherwise, add it to the result.\n\n6. Update the result accordingly for each symbol as you iterate through the string.\n\n7. Finally, return the accumulated result as the integer equivalent of the Roman numeral.\n\n---\n\n# \u2705Complexity\n## 1. Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this code is O(n), where \'n\' is the length of the input string s. This is because we iterate through the entire string once from right to left.\n## 2. Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) because the size of the romanValues map is fixed and does not depend on the input size. We use a constant amount of additional space to store the result and loop variables, so the space complexity is constant.\n\n---\n\n# \uD83D\uDCA1"If you have made it this far, I would like to kindly request that you upvote this solution to ensure its reach extends to others as well."\u2763\uFE0F\uD83D\uDCA1\n\n---\n\n# \u2705Code\n```C++ []\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> romanValues = {\n {\'I\', 1},\n {\'V\', 5},\n {\'X\', 10},\n {\'L\', 50},\n {\'C\', 100},\n {\'D\', 500},\n {\'M\', 1000}\n };\n\n int result = 0;\n\n for (int i = s.length() - 1; i >= 0; i--) {\n int currValue = romanValues[s[i]];\n\n if (i < s.length() - 1 && currValue < romanValues[s[i + 1]]) {\n result -= currValue;\n } else {\n result += currValue;\n }\n }\n\n return result;\n }\n};\n\n```\n```Python []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n romanValues = {\n \'I\': 1,\n \'V\': 5,\n \'X\': 10,\n \'L\': 50,\n \'C\': 100,\n \'D\': 500,\n \'M\': 1000\n }\n\n result = 0\n\n for i in range(len(s) - 1, -1, -1):\n currValue = romanValues[s[i]]\n\n if i < len(s) - 1 and currValue < romanValues[s[i + 1]]:\n result -= currValue\n else:\n result += currValue\n\n return result\n\n```\n```Java []\nimport java.util.HashMap;\nimport java.util.Map;\n\nclass Solution {\n public int romanToInt(String s) {\n Map<Character, Integer> romanValues = new HashMap<>();\n romanValues.put(\'I\', 1);\n romanValues.put(\'V\', 5);\n romanValues.put(\'X\', 10);\n romanValues.put(\'L\', 50);\n romanValues.put(\'C\', 100);\n romanValues.put(\'D\', 500);\n romanValues.put(\'M\', 1000);\n\n int result = 0;\n\n for (int i = s.length() - 1; i >= 0; i--) {\n int currValue = romanValues.get(s.charAt(i));\n\n if (i < s.length() - 1 && currValue < romanValues.get(s.charAt(i + 1))) {\n result -= currValue;\n } else {\n result += currValue;\n }\n }\n\n return result;\n }\n}\n\n```\n```Javascript []\nvar romanToInt = function(s) {\n const romanValues = {\n \'I\': 1,\n \'V\': 5,\n \'X\': 10,\n \'L\': 50,\n \'C\': 100,\n \'D\': 500,\n \'M\': 1000\n };\n\n let result = 0;\n\n for (let i = s.length - 1; i >= 0; i--) {\n const currValue = romanValues[s[i]];\n\n if (i < s.length - 1 && currValue < romanValues[s[i + 1]]) {\n result -= currValue;\n } else {\n result += currValue;\n }\n }\n\n return result;\n};\n\n```\n
1,219
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.
15,697
25
### C#,Java,Python3,JavaScript different solution with explanation\n**\u2B50[]()\u2B50**\n\n**\uD83E\uDDE1See next question solution - [Zyrastory-Longest Common Prefix]()**\n\n\n#### **Example : C# Code ( You can also find an easier solution in the post )**\n```\npublic class Solution {\n private readonly Dictionary<char, int> dict = new Dictionary<char, int>{{\'I\',1},{\'V\',5},{\'X\',10},{\'L\',50},{\'C\',100},{\'D\',500},{\'M\',1000}};\n \n public int RomanToInt(string s) {\n \n char[] ch = s.ToCharArray();\n \n int result = 0;\n int intVal,nextIntVal;\n \n for(int i = 0; i <ch.Length ; i++){\n intVal = dict[ch[i]];\n \n if(i != ch.Length-1)\n {\n nextIntVal = dict[ch[i+1]];\n \n if(nextIntVal>intVal){\n intVal = nextIntVal-intVal;\n i = i+1;\n }\n }\n result = result + intVal;\n }\n return result;\n }\n}\n```\n**\u2B06To see other languages please click the link above\u2B06**\n\nIf you got any problem about the explanation or you need other programming language solution, please feel free to let me know (leave comment or messenger me).\n\n**Thanks!**
1,227
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.
2,091
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}\n\n res = 0\n\n for i in range(len(s)):\n if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]:\n res -= roman[s[i]]\n else:\n res += roman[s[i]]\n return res\n```
1,234
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.
25,992
51
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe essentially start scanning adding all of the corresponding values for each character regardless of order. (e.g. "IX" is 11 not 9) Then, we check the order of the elements, and if we find that the order is reversed (i.e. "IX"), we make the necessary adjustment (e.g. for "IX," we subtract 2)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Introduce the total sum variable, and the dictionary containing the corresponding number values for each Roman letter\n2) We add all of the corresponding number values together regardless of order of elements\n3) We check if certain ordered pairs are in the Roman number and make the adjustments if necessary\n\n\n# Code\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n total = 0\n theDict = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}\n\n for i in s:\n total += theDict[i]\n\n if "IV" in s:\n total -= 2\n if "IX" in s:\n total -= 2\n if "XL" in s:\n total -= 20\n if "XC" in s:\n total -= 20\n if "CD" in s:\n total -= 200\n if "CM" in s:\n total -= 200\n\n \n return total\n```
1,251
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.
13,022
49
# Intuition of this Problem:\nThe given code is implementing the conversion of a Roman numeral string into an integer. It uses an unordered map to store the mapping between Roman numerals and their corresponding integer values. The algorithm takes advantage of the fact that in a valid Roman numeral string, the larger numeral always appears before the smaller numeral if the smaller numeral is subtracted from the larger one. Thus, it starts with the last character in the string and adds the corresponding value to the integer variable. Then, it iterates through the remaining characters from right to left and checks whether the current numeral is greater than or equal to the previous numeral. If it is greater, then it adds the corresponding value to the integer variable, otherwise, it subtracts the corresponding value from the integer variable.\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. Create an unordered map and store the mapping between Roman numerals and their corresponding integer values.\n2. Reverse the input Roman numeral string.\n3. Initialize an integer variable to 0.\n4. Add the integer value corresponding to the last character in the string to the integer variable.\n5. Iterate through the remaining characters from right to left.\n6. Check whether the integer value corresponding to the current character is greater than or equal to the integer value corresponding to the previous character.\n7. If it is greater, add the integer value to the integer variable.\n8. If it is smaller, subtract the integer value from the integer variable.\n9. Return the final integer variable.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n\n![57jfh9.jpg]()\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> storeKeyValue;\n storeKeyValue[\'I\'] = 1;\n storeKeyValue[\'V\'] = 5;\n storeKeyValue[\'X\'] = 10;\n storeKeyValue[\'L\'] = 50;\n storeKeyValue[\'C\'] = 100;\n storeKeyValue[\'D\'] = 500;\n storeKeyValue[\'M\'] = 1000;\n reverse(s.begin(), s.end());\n int integer = 0;\n integer += storeKeyValue[s[0]];\n for (int i = 1; i < s.length(); i++) {\n if(storeKeyValue[s[i]] >= storeKeyValue[s[i-1]])\n integer += storeKeyValue[s[i]];\n else\n integer -= storeKeyValue[s[i]];\n }\n return integer;\n }\n};\n```\n```Java []\nclass Solution {\n public int romanToInt(String s) {\n HashMap<Character, Integer> storeKeyValue = new HashMap<>();\n storeKeyValue.put(\'I\', 1);\n storeKeyValue.put(\'V\', 5);\n storeKeyValue.put(\'X\', 10);\n storeKeyValue.put(\'L\', 50);\n storeKeyValue.put(\'C\', 100);\n storeKeyValue.put(\'D\', 500);\n storeKeyValue.put(\'M\', 1000);\n int integer = 0;\n integer += storeKeyValue.get(s.charAt(0));\n for (int i = 1; i < s.length(); i++) {\n if(storeKeyValue.get(s.charAt(i)) >= storeKeyValue.get(s.charAt(i-1)))\n integer += storeKeyValue.get(s.charAt(i));\n else\n integer -= storeKeyValue.get(s.charAt(i));\n }\n return integer;\n }\n}\n\n```\n```Python []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n storeKeyValue = {}\n storeKeyValue[\'I\'] = 1\n storeKeyValue[\'V\'] = 5\n storeKeyValue[\'X\'] = 10\n storeKeyValue[\'L\'] = 50\n storeKeyValue[\'C\'] = 100\n storeKeyValue[\'D\'] = 500\n storeKeyValue[\'M\'] = 1000\n s = s[::-1]\n integer = 0\n integer += storeKeyValue[s[0]]\n for i in range(1, len(s)):\n if storeKeyValue[s[i]] >= storeKeyValue[s[i-1]]:\n integer += storeKeyValue[s[i]]\n else:\n integer -= storeKeyValue[s[i]]\n return integer\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(s.length()) = O(15) = O(1)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(7) = O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1,256
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.
2,113
8
```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n a={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}\n sum=0 \n x=0\n while x<len(s):\n if x<len(s)-1 and a[s[x]]<a[s[x+1]]:\n sum += (a[s[x+1]] - a[s[x]])\n x += 2\n else:\n sum += a[s[x]]\n x += 1\n return sum\n```
1,265
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
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
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
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
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
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
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
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
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
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?
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?
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?
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?
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?
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
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
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
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
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
53,662
639
This snippet is helpful while preparing for interviews as it groups together similar python Backtracking problems and solution. Feel free to let me know if you have found similar backtracking problems or have any suggestions, will add it to the post.\n\n**78. Subsets:** Runtime: 16 ms, faster than 96.05%\n```\nclass Solution(object):\n def subsets(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n """\n res = []\n self.dfs(nums, [], res)\n return res\n \n def dfs(self, nums, path, res):\n res.append(path)\n for i in range(len(nums)):\n self.dfs(nums[i+1:], path + [nums[i]], res) \n```\n**90. Subsets II:** Runtime: 20 ms, faster than 96.23% \n```\nclass Solution(object):\n def subsetsWithDup(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n """\n res = []\n nums.sort()\n self.dfs(nums, [], res)\n return res\n \n def dfs(self, nums, path, res):\n res.append(path)\n for i in range(len(nums)):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n self.dfs(nums[i+1:], path + [nums[i]], res)\n```\n\n**77. Combinations**: Runtime: 676 ms, faster than 42.96%\n```\nclass Solution(object):\n def combine(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n """\n res=[]\n self.dfs(range(1, n+1), k, [], res)\n return res\n \n def dfs(self, nums, k, path, res):\n if len(path) == k:\n res.append(path)\n return\n for i in range(len(nums)):\n self.dfs(nums[i+1:], k, path+ [nums[i]], res)\n```\n**39. Combination Sum**: Runtime: 124 ms, faster than 30.77%\n```\nclass Solution(object):\n def combinationSum(self, candidates, target):\n """\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n """\n res = []\n candidates.sort()\n self.dfs(candidates, target, [], res)\n return res\n \n def dfs(self, candidates, target, path, res):\n if target < 0:\n return #backtracking\n if target == 0:\n res.append(path)\n return\n for i in range(len(candidates)):\n self.dfs(candidates[i:], target - candidates[i], path + [candidates[i]], res) \n```\n**40. Combination Sum II**: Runtime: 36 ms, faster than 91.77%\n```\nclass Solution(object):\n def combinationSum2(self, candidates, target):\n """\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n """\n res = []\n candidates.sort()\n self.dfs(candidates, target, [], res)\n return res\n \n def dfs(self, candidates, target, path, res):\n if target < 0:\n return\n \n if target == 0:\n res.append(path)\n for i in range(len(candidates)):\n if i > 0 and candidates[i] == candidates[i-1]:\n continue\n \n if candidates[i]> target:\n break\n \n self.dfs(candidates[i+1:], target - candidates[i], path + [candidates[i]], res)\n```\n\n**46. Permutations**: Runtime: 28 ms, faster than 79.64%\n```\nclass Solution(object):\n def permute(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n """\n res = []\n self.dfs(nums, [], res)\n return res\n \n def dfs(self, nums, path, res):\n if len(nums) == 0:\n res.append(path)\n return\n for i in range(len(nums)):\n self.dfs(nums[:i] + nums[i+1:], path + [nums[i]], res) \n```\n\n**47. Permutations II**: Runtime: 40 ms, faster than 92.96%\n```\nclass Solution(object):\n def permuteUnique(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n """\n res = []\n nums.sort()\n self.dfs(nums, [], res)\n return res\n \n def dfs(self, nums, path, res):\n if len(nums) == 0:\n res.append(path)\n for i in range(len(nums)):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n self.dfs(nums[:i] + nums[i+1:], path + [nums[i]], res)\n```\n**17. Letter combination of a Phone Number:**:Runtime: 24 ms, faster than 43.40%\n```\nclass Solution(object):\n def letterCombinations(self, digits):\n """\n :type digits: str\n :rtype: List[str]\n """\n dic = { "2": "abc", "3": "def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}\n \n res=[]\n if len(digits) ==0:\n return res\n \n self.dfs(digits, 0, dic, \'\', res)\n return res\n \n def dfs(self, nums, index, dic, path, res):\n if index >=len(nums):\n res.append(path)\n return\n string1 =dic[nums[index]]\n for i in string1:\n self.dfs(nums, index+1, dic, path + i, res)\n```\n==========================================================\nI hope that you\'ve found the solutions useful. Please do UPVOTE, it only motivates me to write more such posts. Thanks!\n
1,622
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
19,701
122
# Please UPVOTE \uD83D\uDC4D\n\n**!! BIG ANNOUNCEMENT !!**\nI am Giving away my premium content videos related to computer science and data science and also will be sharing well-structured assignments and study materials to clear interviews at top companies to my first 1000 Subscribers. So, **DON\'T FORGET** to Subscribe\n\n\n```\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n if not digits:\n return []\n \n phone = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}\n res = []\n \n def backtrack(combination, next_digits):\n if not next_digits:\n res.append(combination)\n return\n \n for letter in phone[next_digits[0]]:\n backtrack(combination + letter, next_digits[1:])\n \n backtrack("", digits)\n return res\n\n```\n**Explanation:**\n\n- We define a helper function "backtrack" that takes two arguments: the current combination and the remaining digits to process.\n\n- If there are no more digits to process, we append the current combination to the final list and return.\n\n- Otherwise, we iterate through each letter that the first remaining digit maps to, and recursively call the "backtrack" function with the new combination and the remaining digits.\n\n- We initialize the final list "res" to an empty list, and call the "backtrack" function with an empty combination and the original phone number.\n\n- Finally, we return the final list of combinations.\n\n![image.png]()\n\n# Please UPVOTE \uD83D\uDC4D
1,630
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
1,730
8
<iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\npublic:\n vector<string> ans;\n vector<string> dial = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n \n vector<string> letterCombinations(string digits) {\n ans.clear();\n if (digits.length() == 0) {\n return ans;\n }\n helper("", 0, digits);\n return ans;\n }\n \n void helper(string comb, int index, string digits) {\n if (index == digits.length()) {\n ans.push_back(comb);\n return;\n }\n \n string letters = dial[digits[index] - \'0\'];\n for (int i = 0; i < letters.length(); i++) {\n helper(comb + letters[i], index + 1, digits);\n }\n }\n};\n\n```\n\n```\nimport java.util.*;\n\nclass Solution {\n List<String> ans;\n String[] dial = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n \n public List<String> letterCombinations(String digits) {\n ans = new ArrayList<>();\n if (digits.length() == 0) {\n return ans;\n }\n helper("", 0, digits);\n return ans;\n }\n \n private void helper(String comb, int index, String digits) {\n if (index == digits.length()) {\n ans.add(comb);\n return;\n }\n \n String letters = dial[digits.charAt(index) - \'0\'];\n for (int i = 0; i < letters.length(); i++) {\n helper(comb + letters.charAt(i), index + 1, digits);\n }\n }\n}\n\n```\n\n```\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n ans = []\n dial = ["0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]\n \n def helper(comb, index, digits):\n nonlocal ans\n if index == len(digits):\n ans.append(comb)\n return\n \n letters = dial[int(digits[index])]\n for char in letters:\n helper(comb + char, index + 1, digits)\n \n if len(digits) == 0:\n return ans\n \n helper("", 0, digits)\n return ans\n\n```
1,637
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
3,027
33
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Mapping of Digits to Letters:** The problem is similar to generating all possible combinations of characters you can get from pressing the digits on a telephone keypad. We are given a mapping of each digit to a set of letters.\n\n**Backtracking:** Backtracking is a powerful technique used to explore all possible combinations of a problem space by building a solution incrementally and undoing the choices when they don\'t lead to a valid solution. In this problem, we will use backtracking to generate all possible letter combinations.\n\n**Recursive Exploration:** The basic idea is to consider each digit in the input string and explore all the possible letters associated with that digit. We start with the first digit and try each letter associated with it. Then, for each of these choices, we move on to the next digit and repeat the process.\n\n**Base Case:** We use recursion to handle each digit in the input string one by one. The base case for our recursive function will be when we have processed all the digits in the input string. At this point, we have a valid letter combination, and we can add it to the result list.\n\n**Recursive Call and Backtracking:** For each digit, we loop through all its associated letters and make a recursive call to the function with the next digit. During this recursion, we maintain the current combination of letters. After the recursive call, we remove the last letter added to the combination (backtrack) and try the next letter.\n\n**Combination Generation:** As we go deeper into the recursion, the current combination of letters will build up until we reach the base case. At the base case, we have formed a complete letter combination for the given input. We add this combination to the result list and return to the previous level of the recursion to try other possibilities.\n\nBy using the backtracking approach, we can efficiently generate all possible letter combinations for the given input digits. This approach ensures that we explore all valid combinations by making choices and undoing them when needed, ultimately forming the complete set of combinations.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a mapping of digits to letters(Different for different languages). For example:\n```\nmapping = {\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```\n2. Initialize an empty list to store the results.\n\n3. Implement a recursive function that takes the current index and a string representing the current combination. Start with index 0 and an empty string.\n\n4. In the recursive function, if the current index is equal to the length of the input digits, add the current combination to the results list and return.\n\n5. Otherwise, get the letters corresponding to the current digit. For each letter, append it to the current combination and make a recursive call with the next index.\n\n6. After the recursive call, remove the last letter added to the current combination (backtrack) and move on to the next letter.\n\n7. Once the recursive function is completed, return the list of results.\n\n# Complexity\n- **Time complexity:** The time complexity of this approach is O(4^n) where n is the number of digits in the input string. This is because each digit can map to up to 4 letters in the worst case, and there are n digits in the input.\n\n- **Space complexity:** The space complexity is O(n) as we are using recursion and the maximum depth of the recursion is n. Additionally, we are using a result list to store the combinations, which can also take up to O(n) space in the worst case.\n\n# Code\n## C++\n```\nclass Solution {\npublic:\n vector<string> letterCombinations(string digits) {\n vector<string> result;\n if (digits.empty()) return result;\n \n unordered_map<char, string> mapping = {\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 string currentCombination;\n backtrack(digits, 0, mapping, currentCombination, result);\n \n return result;\n }\n \n void backtrack(const string& digits, int index, const unordered_map<char, string>& mapping, string& currentCombination, vector<string>& result) {\n if (index == digits.length()) {\n result.push_back(currentCombination);\n return;\n }\n \n char digit = digits[index];\n string letters = mapping.at(digit);\n for (char letter : letters) {\n currentCombination.push_back(letter);\n backtrack(digits, index + 1, mapping, currentCombination, result);\n currentCombination.pop_back(); // Backtrack by removing the last letter added\n }\n }\n};\n```\n## Java\n```\nclass Solution {\n public List<String> letterCombinations(String digits) {\n List<String> result = new ArrayList<>();\n if (digits.isEmpty()) return result;\n \n Map<Character, String> mapping = new HashMap<>();\n mapping.put(\'2\', "abc");\n mapping.put(\'3\', "def");\n mapping.put(\'4\', "ghi");\n mapping.put(\'5\', "jkl");\n mapping.put(\'6\', "mno");\n mapping.put(\'7\', "pqrs");\n mapping.put(\'8\', "tuv");\n mapping.put(\'9\', "wxyz");\n \n StringBuilder currentCombination = new StringBuilder();\n backtrack(digits, 0, mapping, currentCombination, result);\n \n return result;\n }\n \n private void backtrack(String digits, int index, Map<Character, String> mapping, StringBuilder currentCombination, List<String> result) {\n if (index == digits.length()) {\n result.add(currentCombination.toString());\n return;\n }\n \n char digit = digits.charAt(index);\n String letters = mapping.get(digit);\n for (char letter : letters.toCharArray()) {\n currentCombination.append(letter);\n backtrack(digits, index + 1, mapping, currentCombination, result);\n currentCombination.deleteCharAt(currentCombination.length() - 1); // Backtrack by removing the last letter added\n }\n }\n}\n\n```\n## Pyhton3\n```\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n result = []\n if not digits:\n return result\n \n mapping = {\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(index, current_combination):\n nonlocal result\n if index == len(digits):\n result.append(current_combination)\n return\n \n digit = digits[index]\n letters = mapping[digit]\n for letter in letters:\n backtrack(index + 1, current_combination + letter)\n \n backtrack(0, "")\n return result\n\n```\n![upvote img.jpg]()\n
1,651
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
7,265
21
\n# Intuition:\nThe problem requires finding all possible letter combinations that can be formed by a given sequence of digits. For example, if the input is "23", then the output should contain all possible combinations of the letters \'a\', \'b\', and \'c\' for digit 2, and \'d\', \'e\', and \'f\' for digit 3. This can be solved using a backtracking approach where we start with the first digit and find all the possible letters that can be formed using that digit, and then move on to the next digit and find all the possible letters that can be formed using that digit, and so on until we have formed a combination of all digits.\n\n# Approach:\n\n1. Define a function letterCombinations which takes a string of digits as input and returns a vector of all possible letter combinations.\n2. Check if the input string is empty, if it is, return an empty vector as there are no possible letter combinations.\n3. Define a mapping vector which contains the letters corresponding to each digit. For example, the mapping vector for the input "23" would be {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}.\n4. Define an empty string combination with the same size as the input digits string.\n5. Call the backtrack function with the initial index as 0 and pass the result vector, mapping vector, combination string, and digits string as arguments.\n6. In the backtrack function, check if the current index is equal to the size of the digits string. If it is, that means we have formed a complete combination of letters, so we add the current combination string to the result vector and return.\n7. Otherwise, get the possible letters corresponding to the current digit using the mapping vector.\n8. Iterate through all the possible letters and set the current index of the combination string to that letter.\n9. Call the backtrack function recursively with the incremented index.\n10. After the recursive call returns, reset the current index of the combination string to its previous value so that we can try the next letter.\n# Complexity:\n- Time Complexity:\nThe time complexity of the algorithm is O(3^N \xD7 4^M), where N is the number of digits in the input string that correspond to 3 letters (\'2\', \'3\', \'4\', \'5\', \'6\', \'8\'), and M is the number of digits in the input string that correspond to 4 letters (\'7\', \'9\'). The reason for this is that each digit can correspond to 3 or 4 letters, and we need to generate all possible combinations of these letters. The maximum length of the result vector can be 3^N \xD7 4^M, as each letter can be used at most once in a combination.\n\n- Space Complexity:\nThe space complexity of the algorithm is O(N), where N is the number of digits in the input string. This is because we use a combination string of size N to store the current combination of letters being formed, and a result vector to store all the possible combinations. The mapping vector is of constant size and does not contribute to the space complexity.\n\n---\n\n# C++\n```\nclass Solution {\npublic:\n vector<string> letterCombinations(string digits) {\n vector<string> result;\n if (digits.empty()) {\n return result;\n }\n vector<string> mapping = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n string combination(digits.size(), \' \');\n backtrack(result, mapping, combination, digits, 0);\n return result;\n }\n \nprivate:\n void backtrack(vector<string>& result, const vector<string>& mapping, string& combination, const string& digits, int index) {\n if (index == digits.size()) {\n result.push_back(combination);\n } else {\n string letters = mapping[digits[index] - \'0\'];\n for (char letter : letters) {\n combination[index] = letter;\n backtrack(result, mapping, combination, digits, index + 1);\n }\n }\n }\n};\n\n```\n\n---\n# Java\n```\nclass Solution {\n public List<String> letterCombinations(String digits) {\n List<String> result = new ArrayList<>();\n if (digits == null || digits.length() == 0) {\n return result;\n }\n String[] mapping = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n StringBuilder combination = new StringBuilder();\n backtrack(result, mapping, combination, digits, 0);\n return result;\n }\n\n private void backtrack(List<String> result, String[] mapping, StringBuilder combination, String digits, int index) {\n if (index == digits.length()) {\n result.add(combination.toString());\n } else {\n String letters = mapping[digits.charAt(index) - \'0\'];\n for (char letter : letters.toCharArray()) {\n combination.append(letter);\n backtrack(result, mapping, combination, digits, index + 1);\n combination.deleteCharAt(combination.length() - 1);\n }\n }\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def letterCombinations(self, digits):\n result = []\n if not digits:\n return result\n mapping = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]\n combination = [""] * len(digits)\n self.backtrack(result, mapping, combination, digits, 0)\n return result\n\n def backtrack(self, result, mapping, combination, digits, index):\n if index == len(digits):\n result.append("".join(combination))\n else:\n letters = mapping[int(digits[index])]\n for letter in letters:\n combination[index] = letter\n self.backtrack(result, mapping, combination, digits, index + 1)\n\n```\n\n---\n# JavaScript\n```\nvar letterCombinations = function(digits) {\n const result = [];\n if (!digits) {\n return result;\n }\n const mapping = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];\n const combination = new Array(digits.length).fill(\'\');\n backtrack(result, mapping, combination, digits, 0);\n return result;\n};\n\nfunction backtrack(result, mapping, combination, digits, index) {\n if (index === digits.length) {\n result.push(combination.join(\'\'));\n } else {\n const letters = mapping[digits.charAt(index) - \'0\'];\n for (const letter of letters) {\n combination[index] = letter;\n backtrack(result, mapping, combination, digits, index + 1);\n }\n }\n}\n\n```
1,662
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
9,595
26
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nExplore all the choices and build the answer.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\n\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nApproach for `solve`:\n\n- It takes a string `digits` and an array `arr` as input.\n- Base case: If the input `digits` is empty, return a vector containing an empty string, representing the empty combination.\n- Get the first digit `c` from the `digits` string and its corresponding letters `a` from the `arr` array.\n- Recursively call `solve` with the remaining digits `smallinput` (excluding the first digit) and the `arr` array.\n- For each returned combination `x` from the recursive call, iterate through each letter `x1` in the string `a`.\n- Append `x1` to `x`, representing the current letter combination for the first digit `c`.\n- Add the new combination `x1 + x` to the result vector `res`.\n- Return the vector `res` containing all generated combinations.\n\nApproach for `solve2`:\n\n- It takes a string `digits`, an array `arr`, an index `i`, and a current combination `com` as input.\n- Base case: If the index `i` reaches the size of the `digits` string, it means all digits have been processed. In this case, add the current combination `com` to the final result vector.\n- Get the current digit `c` from the `digits` string and its corresponding letters `a` from the `arr` array using the digit as an index.\n- Loop through each letter `a[k]` in `a`.\n- Append `a[k]` to the current combination `com`.\n- Make a recursive call to `solve2` with the next index `i+1` and the updated combination `com`.\n- This recursive process explores all possible combinations of letters for the given digits.\n- The final result will be stored in the `ans` vector, which accumulates all valid combinations.\n\n\n\n# Complexity\n- Time complexity:$$O(4^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```C++ []\nclass Solution {\npublic:\n vector<string>solve(string digits,string*arr){\n if(digits.size()==0){\n vector<string>bs;\n bs.push_back("");\n return bs;\n }\n \n char c=digits[0];\n string a=arr[c-\'0\'];\n string smallinput=digits.substr(1);\n vector<string>rest=solve(smallinput,arr);\n vector<string>res;\n for(auto x:rest){\n for(auto x1:a){\n res.push_back(x1+x);\n } \n }\n return res;\n }\n vector<string>ans;\n void solve2(string digits,string *arr,int i,string com){\n if(i==digits.size()){\n ans.push_back(com);\n return;\n }\n char c=digits[i];\n string a=arr[c-\'0\'];\n for(int k=0;k<a.size();k++){\n solve2(digits,arr,i+1,com+a[k]);\n }\n }\n vector<string> letterCombinations(string digits) {\n vector<string>a;\n if(digits.size()==0)\n return a;\n string arr[]={"0","0","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};\n // vector<string>ans=solve(digits,arr);\n solve2(digits,arr,0,"");\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n private List<String> solve(String digits, String[] arr) {\n if (digits.length() == 0) {\n List<String> bs = new ArrayList<>();\n bs.add("");\n return bs;\n }\n\n char c = digits.charAt(0);\n String a = arr[c - \'0\'];\n String smallinput = digits.substring(1);\n List<String> rest = solve(smallinput, arr);\n List<String> res = new ArrayList<>();\n for (String x : rest) {\n for (char x1 : a.toCharArray()) {\n res.add(x1 + x);\n }\n }\n return res;\n }\n\n private List<String> ans = new ArrayList<>();\n\n private void solve2(String digits, String[] arr, int i, String com) {\n if (i == digits.length()) {\n ans.add(com);\n return;\n }\n char c = digits.charAt(i);\n String a = arr[c - \'0\'];\n for (char x1 : a.toCharArray()) {\n solve2(digits, arr, i + 1, com + x1);\n }\n }\n\n public List<String> letterCombinations(String digits) {\n List<String> a = new ArrayList<>();\n if (digits.length() == 0)\n return a;\n String[] arr = {"0", "0", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n solve2(digits, arr, 0, "");\n return ans;\n }\n}\n```\n```python []\nclass Solution:\n def solve(self, digits, arr):\n if not digits:\n return [""]\n\n c = digits[0]\n a = arr[int(c)]\n small_input = digits[1:]\n rest = self.solve(small_input, arr)\n res = []\n for x in rest:\n for x1 in a:\n res.append(x1 + x)\n return res\n\n def __init__(self):\n self.ans = []\n\n def solve2(self, digits, arr, i, com):\n if i == len(digits):\n self.ans.append(com)\n return\n\n c = digits[i]\n a = arr[int(c)]\n for x1 in a:\n self.solve2(digits, arr, i + 1, com + x1)\n\n def letterCombinations(self, digits):\n a = []\n if not digits:\n return a\n arr = ["0", "0", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]\n self.solve2(digits, arr, 0, "")\n return self.ans\n\n```\n\n
1,675
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,719
19
# Intuition\nUsing backtracking to create all possible combinations\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n\n\n\n# Subscribe to my channel from here. I have 239 videos as of August 3rd\n\n\n---\n\n\n# Approach\nThis is based on Python solution. Other might be differnt a bit.\n\n1. Initialize an empty list `res` to store the generated combinations.\n\n2. Check if the `digits` string is empty. If it is, return an empty list since there are no digits to process.\n\n3. Create a dictionary `digit_to_letters` that maps each digit from \'2\' to \'9\' to the corresponding letters on a phone keypad.\n\n4. Define a recursive function `backtrack(idx, comb)` that takes two parameters:\n - `idx`: The current index of the digit being processed in the `digits` string.\n - `comb`: The current combination being formed by appending letters.\n\n5. Inside the `backtrack` function:\n - Check if `idx` is equal to the length of the `digits` string. If it is, it means a valid combination has been formed, so append the current `comb` to the `res` list.\n - If not, iterate through each letter corresponding to the digit at `digits[idx]` using the `digit_to_letters` dictionary.\n - For each letter, recursively call `backtrack` with `idx + 1` to process the next digit and `comb + letter` to add the current letter to the combination.\n\n6. Initialize the `res` list.\n\n7. Start the initial call to `backtrack` with `idx` set to 0 and an empty string as `comb`. This will start the process of generating combinations.\n\n8. After the recursive calls have been made, return the `res` list containing all the generated combinations.\n\nThe algorithm works by iteratively exploring all possible combinations of letters that can be formed from the given input digits. It uses a recursive approach to generate combinations, building them one letter at a time. The base case for the recursion is when all digits have been processed, at which point a combination is complete and added to the `res` list. The backtracking nature of the algorithm ensures that all possible combinations are explored.\n\n# Complexity\n- Time complexity: O(3^n) or O(4^n)\nn is length of input string. Each digit has 3 or 4 letters. For example, if you get "23"(n) as input string, we will create 9 combinations which is O(3^2) = 9\n\n- Space complexity: O(n)\nn is length of input string. This is for recursive call stack.\n\n```python []\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n if not digits:\n return []\n \n digit_to_letters = {\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(idx, comb):\n if idx == len(digits):\n res.append(comb[:])\n return\n \n for letter in digit_to_letters[digits[idx]]:\n backtrack(idx + 1, comb + letter)\n\n res = []\n backtrack(0, "")\n\n return res\n```\n```javascript []\n/**\n * @param {string} digits\n * @return {string[]}\n */\nvar letterCombinations = function(digits) {\n if (!digits.length) {\n return [];\n }\n \n const digitToLetters = {\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 const res = [];\n \n function backtrack(idx, comb) {\n if (idx === digits.length) {\n res.push(comb);\n return;\n }\n \n for (const letter of digitToLetters[digits[idx]]) {\n backtrack(idx + 1, comb + letter);\n }\n }\n \n backtrack(0, "");\n \n return res; \n};\n```\n```Java []\nclass Solution {\n public List<String> letterCombinations(String digits) {\n List<String> res = new ArrayList<>();\n \n if (digits == null || digits.length() == 0) {\n return res;\n }\n \n Map<Character, String> digitToLetters = new HashMap<>();\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 backtrack(digits, 0, new StringBuilder(), res, digitToLetters);\n \n return res; \n }\n\n private void backtrack(String digits, int idx, StringBuilder comb, List<String> res, Map<Character, String> digitToLetters) {\n if (idx == digits.length()) {\n res.add(comb.toString());\n return;\n }\n \n String letters = digitToLetters.get(digits.charAt(idx));\n for (char letter : letters.toCharArray()) {\n comb.append(letter);\n backtrack(digits, idx + 1, comb, res, digitToLetters);\n comb.deleteCharAt(comb.length() - 1);\n }\n } \n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<string> letterCombinations(string digits) {\n vector<string> res;\n \n if (digits.empty()) {\n return res;\n }\n \n unordered_map<char, string> digitToLetters = {\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 backtrack(digits, 0, "", res, digitToLetters);\n \n return res; \n }\n\n void backtrack(const string& digits, int idx, string comb, vector<string>& res, const unordered_map<char, string>& digitToLetters) {\n if (idx == digits.length()) {\n res.push_back(comb);\n return;\n }\n \n string letters = digitToLetters.at(digits[idx]);\n for (char letter : letters) {\n backtrack(digits, idx + 1, comb + letter, res, digitToLetters);\n }\n } \n};\n```\n
1,681
4Sum
4sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order.
Array,Two Pointers,Sorting
Medium
null
1,829
21
# Intuition\n* It first checks if there are fewer than 4 elements in the input array. If so, it returns an empty vector since there can\'t be any valid quadruplets.\n\n* It sorts the input array in ascending order to simplify the process of finding unique quadruplets.\n\n* It initializes a temporary vector temp to store combinations and a result vector res to store valid quadruplets.\n\n* It calls the helper function with the sorted array, target value, and other parameters to find quadruplets.\n\n* The helper function uses recursion to find unique combinations of numbers. It has two modes of operation: when it needs more than 2 numbers to complete the combination (in this case, it searches for the first number in the combination), and when it needs exactly 2 numbers (in this case, it performs a two-pointer approach).\n\n* In the two-pointer approach, it uses two pointers, l and r, that start from the beginning and end of the sorted array. It calculates the sum of two elements and adjusts the pointers accordingly to find all pairs of numbers that sum up to the target.( Same as 1.TWO_SUM )\n\n* It avoids duplicates in both modes of operation to ensure that the result contains only unique quadruplets.\n\n* Valid quadruplets found during the process are stored in the res vector.\n\n* Finally, it returns the res vector containing all unique quadruplets.\n\n# CPP\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n if (nums.size() < 4) {\n return {}; // If there are fewer than 4 elements, return an empty vector.\n }\n sort(nums.begin(), nums.end()); // Sort the input array in ascending order.\n vector<int> temp; // Temporary vector to store combinations.\n vector<vector<int>> res; // Result vector to store valid quadruplets.\n helper(nums, target, 0, res, temp, 4); // Call the helper function to find quadruplets.\n return res; // Return the result vector containing unique quadruplets.\n }\n \n // Helper function to find unique quadruplets using recursion.\n void helper(vector<int>& nums, long target, int start, vector<vector<int>>& res, vector<int>& temp, int numneed) {\n // If we need more than 2 numbers, we\'re looking for the first number in the combination.\n if (numneed != 2) {\n for (int i = start; i < nums.size() - numneed + 1; i++) {\n if (i > start && nums[i] == nums[i - 1]) {\n continue; // Skip duplicates to avoid duplicate combinations.\n }\n temp.push_back(nums[i]); // Add the current number to the combination.\n helper(nums, target - nums[i], i + 1, res, temp, numneed - 1); // Recursively find the next number(s).\n temp.pop_back(); // Remove the last number to backtrack.\n }\n return;\n }\n \n // If we need exactly 2 numbers, perform a two-pointer approach.\n int l = start;\n int r = nums.size() - 1;\n while (l < r) {\n long sum = static_cast<long>(nums[l]) + static_cast<long>(nums[r]);\n if (sum < target) {\n l++;\n } else if (sum > target) {\n r--;\n } else {\n temp.push_back(nums[l]); // Add the left number to the combination.\n temp.push_back(nums[r]); // Add the right number to the combination.\n res.push_back(temp); // Store the valid quadruplet in the result vector.\n temp.pop_back(); // Remove the right number to backtrack.\n temp.pop_back(); // Remove the left number to backtrack.\n l++;\n r--;\n while (l < r && nums[l] == nums[l - 1]) {\n l++; // Skip duplicates on the left.\n }\n }\n }\n }\n};\n```\n# JAVA\n``` \nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n Arrays.sort(nums); // Sort the input array in ascending order.\n List<List<Integer>> result = new ArrayList<>();\n List<Integer> temp = new ArrayList<>();\n helper(nums, (long) target, 0, result, temp, 4); // Use long data type for target.\n return result; // Return the result list containing unique quadruplets.\n }\n\n private void helper(int[] nums, long target, int start, List<List<Integer>> result, List<Integer> temp, int numNeed) {\n if (numNeed != 2) {\n for (int i = start; i < nums.length - numNeed + 1; i++) {\n if (i > start && nums[i] == nums[i - 1]) {\n continue; // Skip duplicates to avoid duplicate combinations.\n }\n temp.add(nums[i]); // Add the current number to the combination.\n helper(nums, target - nums[i], i + 1, result, temp, numNeed - 1); // Recursively find the next number(s).\n temp.remove(temp.size() - 1); // Remove the last number to backtrack.\n }\n return;\n }\n\n // If we need exactly 2 numbers, perform a two-pointer approach.\n int l = start;\n int r = nums.length - 1;\n while (l < r) {\n long total = (long) nums[l] + nums[r];\n if (total < target) {\n l++;\n } else if (total > target) {\n r--;\n } else {\n temp.add(nums[l]); // Add the left number to the combination.\n temp.add(nums[r]); // Add the right number to the combination.\n result.add(new ArrayList<>(temp)); // Store the valid quadruplet in the result list.\n temp.remove(temp.size() - 1); // Remove the right number to backtrack.\n temp.remove(temp.size() - 1); // Remove the left number to backtrack.\n l++;\n r--;\n while (l < r && nums[l] == nums[l - 1]) {\n l++; // Skip duplicates on the left.\n }\n }\n }\n }\n}\n```\n# PYTHON\n```\nclass Solution:\n def fourSum(self, nums, target):\n def helper(nums, target, start, res, temp, num_need):\n if num_need != 2:\n for i in range(start, len(nums) - num_need + 1):\n if i > start and nums[i] == nums[i - 1]:\n continue # Skip duplicates to avoid duplicate combinations.\n temp.append(nums[i]) # Add the current number to the combination.\n helper(nums, target - nums[i], i + 1, res, temp, num_need - 1) # Recursively find the next number(s).\n temp.pop() # Remove the last number to backtrack.\n return\n\n # If we need exactly 2 numbers, perform a two-pointer approach.\n l, r = start, len(nums) - 1\n while l < r:\n total = nums[l] + nums[r]\n if total < target:\n l += 1\n elif total > target:\n r -= 1\n else:\n temp.append(nums[l]) # Add the left number to the combination.\n temp.append(nums[r]) # Add the right number to the combination.\n res.append(temp[:]) # Store the valid quadruplet in the result list.\n temp.pop() # Remove the right number to backtrack.\n temp.pop() # Remove the left number to backtrack.\n l += 1\n r -= 1\n while l < r and nums[l] == nums[l - 1]:\n l += 1 # Skip duplicates on the left.\n\n nums.sort() # Sort the input list in ascending order.\n res = [] # Result list to store valid quadruplets.\n temp = [] # Temporary list to store combinations.\n helper(nums, target, 0, res, temp, 4) # Call the helper function to find quadruplets.\n return res # Return the result list containing unique quadruplets.\n```\n\n![R.jpg]()\n\n
1,707
4Sum
4sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order.
Array,Two Pointers,Sorting
Medium
null
119,981
641
The core is to implement a fast 2-pointer to solve 2-sum, and recursion to reduce the N-sum to 2-sum. Some optimization was be made knowing the list is sorted.\n\n def fourSum(self, nums, target):\n nums.sort()\n results = []\n self.findNsum(nums, target, 4, [], results)\n return results\n \n def findNsum(self, nums, target, N, result, results):\n if len(nums) < N or N < 2: return\n \n # solve 2-sum\n if N == 2:\n l,r = 0,len(nums)-1\n while l < r:\n if nums[l] + nums[r] == target:\n results.append(result + [nums[l], nums[r]])\n l += 1\n r -= 1\n while l < r and nums[l] == nums[l - 1]:\n l += 1\n while r > l and nums[r] == nums[r + 1]:\n r -= 1\n elif nums[l] + nums[r] < target:\n l += 1\n else:\n r -= 1\n else:\n for i in range(0, len(nums)-N+1): # careful about range\n if target < nums[i]*N or target > nums[-1]*N: # take advantages of sorted list\n break\n if i == 0 or i > 0 and nums[i-1] != nums[i]: # recursively reduce N\n self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)\n return\n\n\nJust revisited and clean the code\n\n\n def fourSum(self, nums, target):\n def findNsum(nums, target, N, result, results):\n if len(nums) < N or N < 2 or target < nums[0]*N or target > nums[-1]*N: # early termination\n return\n if N == 2: # two pointers solve sorted 2-sum problem\n l,r = 0,len(nums)-1\n while l < r:\n s = nums[l] + nums[r]\n if s == target:\n results.append(result + [nums[l], nums[r]])\n l += 1\n while l < r and nums[l] == nums[l-1]:\n l += 1\n elif s < target:\n l += 1\n else:\n r -= 1\n else: # recursively reduce N\n for i in range(len(nums)-N+1):\n if i == 0 or (i > 0 and nums[i-1] != nums[i]):\n findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)\n\n results = []\n findNsum(sorted(nums), target, 4, [], results)\n return results\n\t\t\t\t\npassing pointers, not sliced list\n\n def fourSum(self, nums, target):\n def findNsum(l, r, target, N, result, results):\n if r-l+1 < N or N < 2 or target < nums[l]*N or target > nums[r]*N: # early termination\n return\n if N == 2: # two pointers solve sorted 2-sum problem\n while l < r:\n s = nums[l] + nums[r]\n if s == target:\n results.append(result + [nums[l], nums[r]])\n l += 1\n while l < r and nums[l] == nums[l-1]:\n l += 1\n elif s < target:\n l += 1\n else:\n r -= 1\n else: # recursively reduce N\n for i in range(l, r+1):\n if i == l or (i > l and nums[i-1] != nums[i]):\n findNsum(i+1, r, target-nums[i], N-1, result+[nums[i]], results)\n\n nums.sort()\n results = []\n findNsum(0, len(nums)-1, target, 4, [], results)\n return results
1,708
4Sum
4sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order.
Array,Two Pointers,Sorting
Medium
null
10,006
68
# Intuition of this Problem:\nSet is used to prevent duplicate quadruplets and parallely we will use two pointer approach to maintain k and l.\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 of integers nums.\n2. Initialize an empty set s, and an empty 2D vector output.\n3. Use nested loops to iterate through all possible combinations of quadruplets in nums.\n4. For each combination, use two pointers (k and l) to traverse the sub-array between the second and second-to-last elements of the combination.\n5. At each iteration of the innermost while loop, calculate the sum of the current quadruplet and check if it is equal to the target.\n6. If the sum is equal to the target, insert the quadruplet into the set s and increment both pointers (k and l).\n7. If the sum is less than the target, increment the pointer k.\n8. If the sum is greater than the target, decrement the pointer l.\n9. After all quadruplets have been checked, iterate through the set s and add each quadruplet to the output vector.\n10. Return the output vector.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n\n![57jfh9.jpg]()\n\n# Code:\n```C++ []\n//Optimized Approach using two pointer - O(n^3) time and O(n) space\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\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 int k = j + 1;\n int l = nums.size() - 1;\n while (k < l) {\n //by writing below 4 statement this way it will not give runtime error\n long long int sum = nums[i];\n sum += nums[j];\n sum += nums[k];\n sum += nums[l];\n if (sum == target) {\n s.insert({nums[i], nums[j], nums[k], nums[l]});\n k++;\n l--;\n } else if (sum < target) {\n k++;\n } else {\n l--;\n }\n }\n }\n }\n for(auto quadruplets : s)\n output.push_back(quadruplets);\n return output;\n }\n};\n```\n```C++ []\n//Brute force Approach - O(n^4) time and O(n) space\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\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 for(int l = k+1; l < nums.size(); l++){\n vector<int> temp;\n if(nums[i] + nums[j] + nums[k] + nums[l] == target){\n temp.push_back(nums[i]);\n temp.push_back(nums[j]);\n temp.push_back(nums[k]);\n temp.push_back(nums[l]);\n s.insert(temp);\n }\n }\n }\n }\n }\n for(auto quadruplets : s)\n output.push_back(quadruplets);\n return output;\n }\n};\n```\n```C++ []\n// this peice of code will give runtime error: signed integer overflow: 2000000000 + 1000000000 cannot be represented in type \'int\' for below test case\nnums = [1000000000,1000000000,1000000000,1000000000]\ntarget = 0\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\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 int k = j + 1;\n int l = nums.size() - 1;\n while (k < l) {\n //for below statement it will give runtime error\n long long int sum = nums[i] + nums[j] + nums[k] + nums[l];\n if (sum == target) {\n s.insert({nums[i], nums[j], nums[k], nums[l]});\n k++;\n l--;\n } else if (sum < target) {\n k++;\n } else {\n l--;\n }\n }\n }\n }\n for(auto quadruplets : s)\n output.push_back(quadruplets);\n return output;\n }\n};\n```\n```Java []\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\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 for (int j = i + 1; j < nums.length; j++) {\n int k = j + 1;\n int l = nums.length - 1;\n while (k < l) {\n long sum = nums[i];\n sum += nums[j];\n sum += nums[k];\n sum += nums[l];\n if (sum == target) {\n s.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));\n k++;\n l--;\n } else if (sum < target) {\n k++;\n } else {\n l--;\n }\n }\n }\n }\n output.addAll(s);\n return output;\n }\n}\n\n```\n```Python []\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n nums.sort()\n s = set()\n output = []\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n k = j + 1\n l = len(nums) - 1\n while k < l:\n sum = nums[i] + nums[j] + nums[k] + nums[l]\n if sum == target:\n s.add((nums[i], nums[j], nums[k], nums[l]))\n k += 1\n l -= 1\n elif sum < target:\n k += 1\n else:\n l -= 1\n output = list(s)\n return output\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(n^3)** // where n is the size of array\n\nThe outer two loops have a time complexity of O(n^2) and the inner while loop has a time complexity of O(n). The total time complexity is therefore O(n^2) * O(n) = O(n^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\n\nThe set s stores all unique quadruplets, which in the worst case scenario is O(n).\nThe output vector stores the final output, which is also O(n).\nThe total space complexity is therefore O(n) + O(n) = O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1,709
4Sum
4sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order.
Array,Two Pointers,Sorting
Medium
null
10,830
146
If you\'re a newbie and sometimes have a hard time understanding the logic. Don\'t worry, you\'ll catch up after a month of doing Leetcode on a daily basis. Try to do it, even one example per day. It\'d help. I\'ve compiled a bunch on `sum` problems here, go ahead and check it out. Also, I think focusing on a subject and do 3-4 problems would help to get the idea behind solution since they mostly follow the same logic. Of course there are other ways to solve each problems but I try to be as uniform as possible. Good luck. \n\nIn general, `sum` problems can be categorized into two categories: 1) there is any array and you add some numbers to get to (or close to) a `target`, or 2) you need to return indices of numbers that sum up to a (or close to) a `target` value. Note that when the problem is looking for a indices, `sort`ing the array is probably NOT a good idea. \n\n\n **[Two Sum:]()** \n \n This is the second type of the problems where we\'re looking for indices, so sorting is not necessary. What you\'d want to do is to go over the array, and try to find two integers that sum up to a `target` value. Most of the times, in such a problem, using dictionary (hastable) helps. You try to keep track of you\'ve observations in a dictionary and use it once you get to the results. \n\nNote: try to be comfortable to use `enumerate` as it\'s sometime out of comfort zone for newbies. `enumerate` comes handy in a lot of problems (I mean if you want to have a cleaner code of course). If I had to choose three built in functions/methods that I wasn\'t comfortable with at the start and have found them super helpful, I\'d probably say `enumerate`, `zip` and `set`. \n \nSolution: In this problem, you initialize a dictionary (`seen`). This dictionary will keep track of numbers (as `key`) and indices (as `value`). So, you go over your array (line `#1`) using `enumerate` that gives you both index and value of elements in array. As an example, let\'s do `nums = [2,3,1]` and `target = 3`. Let\'s say you\'re at index `i = 0` and `value = 2`, ok? you need to find `value = 1` to finish the problem, meaning, `target - 2 = 1`. 1 here is the `remaining`. Since `remaining + value = target`, you\'re done once you found it, right? So when going through the array, you calculate the `remaining` and check to see whether `remaining` is in the `seen` dictionary (line `#3`). If it is, you\'re done! you\'re current number and the remaining from `seen` would give you the output (line `#4`). Otherwise, you add your current number to the dictionary (line `#5`) since it\'s going to be a `remaining` for (probably) a number you\'ll see in the future assuming that there is at least one instance of answer. \n \n \n ```\n class Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n seen = {}\n for i, value in enumerate(nums): #1\n remaining = target - nums[i] #2\n \n if remaining in seen: #3\n return [i, seen[remaining]] #4\n else:\n seen[value] = i #5\n```\n \n \n\n **[Two Sum II:]()** \n\nFor this, you can do exactly as the previous. The only change I made below was to change the order of line `#4`. In the previous example, the order didn\'t matter. But, here the problem asks for asending order and since the values/indicess in `seen` has always lower indices than your current number, it should come first. Also, note that the problem says it\'s not zero based, meaning that indices don\'t start from zero, that\'s why I added 1 to both of them. \n\n```\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n \n seen = {}\n for i, value in enumerate(numbers): \n remaining = target - numbers[i] \n \n if remaining in seen: \n return [seen[remaining]+1, i+1] #4\n else:\n seen[value] = i \n```\n\nAnother approach to solve this problem (probably what Leetcode is looking for) is to treat it as first category of problems. Since the array is already sorted, this works. You see the following approach in a lot of problems. What you want to do is to have two pointer (if it was 3sum, you\'d need three pointers as you\'ll see in the future examples). One pointer move from `left` and one from `right`. Let\'s say you `numbers = [1,3,6,9]` and your `target = 10`. Now, `left` points to 1 at first, and `right` points to 9. There are three possibilities. If you sum numbers that `left` and `right` are pointing at, you get `temp_sum` (line `#1`). If `temp_sum` is your target, you\'r done! You\'re return it (line `#9`). If it\'s more than your `target`, it means that `right` is poiting to a very large value (line `#5`) and you need to bring it a little bit to the left to a smaller (r maybe equal) value (line `#6`) by adding one to the index . If the `temp_sum` is less than `target` (line `#7`), then you need to move your `left` to a little bit larger value by adding one to the index (line `#9`). This way, you try to narrow down the range in which you\'re looking at and will eventually find a couple of number that sum to `target`, then, you\'ll return this in line `#9`. In this problem, since it says there is only one solution, nothing extra is necessary. However, when a problem asks to return all combinations that sum to `target`, you can\'t simply return the first instace and you need to collect all the possibilities and return the list altogether (you\'ll see something like this in the next example). \n\n```\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n \n for left in range(len(numbers) -1): #1\n right = len(numbers) - 1 #2\n while left < right: #3\n temp_sum = numbers[left] + numbers[right] #4\n if temp_sum > target: #5\n right -= 1 #6\n elif temp_sum < target: #7\n left +=1 #8\n else:\n return [left+1, right+1] #9\n```\n\n\n\n\n[**3Sum**]()\n\nThis is similar to the previous example except that it\'s looking for three numbers. There are some minor differences in the problem statement. It\'s looking for all combinations (not just one) of solutions returned as a list. And second, it\'s looking for unique combination, repeatation is not allowed. \n\nHere, instead of looping (line `#1`) to `len(nums) -1`, we loop to `len(nums) -2` since we\'re looking for three numbers. Since we\'re returning values, `sort` would be a good idea. Otherwise, if the `nums` is not sorted, you cannot reducing `right` pointer or increasing `left` pointer easily, makes sense? \n\nSo, first you `sort` the array and define `res = []` to collect your outputs. In line `#2`, we check wether two consecutive elements are equal or not because if they are, we don\'t want them (solutions need to be unique) and will skip to the next set of numbers. Also, there is an additional constrain in this line that `i > 0`. This is added to take care of cases like `nums = [1,1,1]` and `target = 3`. If we didn\'t have `i > 0`, then we\'d skip the only correct solution and would return `[]` as our answer which is wrong (correct answer is `[[1,1,1]]`. \n\nWe define two additional pointers this time, `left = i + 1` and `right = len(nums) - 1`. For example, if `nums = [-2,-1,0,1,2]`, all the points in the case of `i=1` are looking at: `i` at `-1`, `left` at `0` and `right` at `2`. We then check `temp` variable similar to the previous example. There is only one change with respect to the previous example here between lines `#5` and `#10`. If we have the `temp = target`, we obviously add this set to the `res` in line `#5`, right? However, we\'re not done yet. For a fixed `i`, we still need to check and see whether there are other combinations by just changing `left` and `right` pointers. That\'s what we are doing in lines `#6, 7, 8`. If we still have the condition of `left < right` and `nums[left]` and the number to the right of it are not the same, we move `left` one index to right (line `#6`). Similarly, if `nums[right]` and the value to left of it is not the same, we move `right` one index to left. This way for a fixed `i`, we get rid of repeative cases. For example, if `nums = [-3, 1,1, 3,5]` and `target = 3`, one we get the first `[-3,1,5]`, `left = 1`, but, `nums[2]` is also 1 which we don\'t want the `left` variable to look at it simply because it\'d again return `[-3,1,5]`, right? So, we move `left` one index. Finally, if the repeating elements don\'t exists, lines `#6` to `#8` won\'t get activated. In this case we still need to move forward by adding 1 to `left` and extracting 1 from `right` (lines `#9, 10`). \n\n```\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n \n nums.sort()\n res = []\n\n for i in range(len(nums) -2): #1\n if i > 0 and nums[i] == nums[i-1]: #2\n continue\n left = i + 1 #3\n right = len(nums) - 1 #4\n \n while left < right: \n temp = nums[i] + nums[left] + nums[right]\n \n if temp > 0:\n right -= 1\n \n elif temp < 0:\n left += 1\n \n else:\n res.append([nums[i], nums[left], nums[right]]) #5\n while left < right and nums[left] == nums[left + 1]: #6\n left += 1\n while left < right and nums[right] == nums[right-1]:#7\n right -= 1 #8\n \n right -= 1 #9 \n left += 1 #10\n \n```\n\nAnother way to solve this problem is to change it into a two sum problem. Instead of finding `a+b+c = 0`, you can find `a+b = -c` where we want to find two numbers `a` and `b` that are equal to `-c`, right? This is similar to the first problem. Remember if you wanted to use the exact same as the first code, it\'d return indices and not numbers. Also, we need to re-arrage this problem in a way that we have `nums` and `target`. This code is not a good code and can be optimipized but you got the idea. For a better version of this, check [this](). \n\n```\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n res = []\n nums.sort()\n \n for i in range(len(nums)-2):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n output_2sum = self.twoSum(nums[i+1:], -nums[i])\n if output_2sum ==[]:\n continue\n else:\n for idx in output_2sum:\n instance = idx+[nums[i]]\n res.append(instance)\n \n output = []\n for idx in res:\n if idx not in output:\n output.append(idx)\n \n \n return output\n \n \n def twoSum(self, nums, target):\n seen = {}\n res = []\n for i, value in enumerate(nums): #1\n remaining = target - nums[i] #2\n \n if remaining in seen: #3\n res.append([value, remaining]) #4\n else:\n seen[value] = i #5\n \n return res\n```\n\n[**4Sum**]()\n\nYou should have gotten the idea, and what you\'ve seen so far can be generalized to `nSum`. Here, I write the generic code using the same ideas as before. What I\'ll do is to break down each case to a `2Sum II` problem, and solve them recursively using the approach in `2Sum II` example above. \n\nFirst sort `nums`, then I\'m using two extra functions, `helper` and `twoSum`. The `twoSum` is similar to the `2sum II` example with some modifications. It doesn\'t return the first instance of results, it check every possible combinations and return all of them now. Basically, now it\'s more similar to the `3Sum` solution. Understanding this function shouldn\'t be difficult as it\'s very similar to `3Sum`. As for `helper` function, it first tries to check for cases that don\'t work (line `#1`). And later, if the `N` we need to sum to get to a `target` is 2 (line `#2`), then runs the `twoSum` function. For the more than two numbers, it recursively breaks them down to two sum (line `#3`). There are some cases like line `#4` that we don\'t need to proceed with the algorithm anymore and we can `break`. These cases include if multiplying the lowest number in the list by `N` is more than `target`. Since its sorted array, if this happens, we can\'t find any result. Also, if the largest array (`nums[-1]`) multiplied by `N` would be less than `target`, we can\'t find any solution. So, `break`. \n\n\nFor other cases, we run the `helper` function again with new inputs, and we keep doing it until we get to `N=2` in which we use `twoSum` function, and add the results to get the final output. \n\n```\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n nums.sort()\n results = []\n self.helper(nums, target, 4, [], results)\n return results\n \n def helper(self, nums, target, N, res, results):\n \n if len(nums) < N or N < 2: #1\n return\n if N == 2: #2\n output_2sum = self.twoSum(nums, target)\n if output_2sum != []:\n for idx in output_2sum:\n results.append(res + idx)\n \n else: \n for i in range(len(nums) -N +1): #3\n if nums[i]*N > target or nums[-1]*N < target: #4\n break\n if i == 0 or i > 0 and nums[i-1] != nums[i]: #5\n self.helper(nums[i+1:], target-nums[i], N-1, res + [nums[i]], results)\n \n \n def twoSum(self, nums: List[int], target: int) -> List[int]:\n res = []\n left = 0\n right = len(nums) - 1 \n while left < right: \n temp_sum = nums[left] + nums[right] \n\n if temp_sum == target:\n res.append([nums[left], nums[right]])\n right -= 1\n left += 1\n while left < right and nums[left] == nums[left - 1]:\n left += 1\n while right > left and nums[right] == nums[right + 1]:\n right -= 1\n \n elif temp_sum < target: \n left +=1 \n else: \n right -= 1\n \n return res\n```\n\n[**Combination Sum II**]()\nI don\'t post combination sum here since it\'s basically this problem a little bit easier. \nCombination questions can be solved with `dfs` most of the time. if you want to fully understand this concept and [backtracking](.***.org/backtracking-introduction/), try to finish [this]() post and do all the examples. \n\nRead my older post first [here](). This should give you a better idea of what\'s going on. The solution here also follow the exact same format except for some minor changes. I first made a minor change in the `dfs` function where it doesn\'t need the `index` parameter anymore. This is taken care of by `candidates[i+1:]` in line `#3`. Note that we had `candidates` here in the previous post. \n\n```\nclass Solution(object):\n def combinationSum2(self, candidates, target):\n """\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n """\n res = []\n candidates.sort()\n self.dfs(candidates, target, [], res)\n return res\n \n \n def dfs(self, candidates, target, path, res):\n if target < 0:\n return\n \n if target == 0:\n res.append(path)\n return res\n \n for i in range(len(candidates)):\n if i > 0 and candidates[i] == candidates[i-1]: #1\n continue #2\n self.dfs(candidates[i+1:], target - candidates[i], path+[candidates[i]], res) #3\n```\n\n\nThe only differences are lines `#1, 2, 3`. The difference in problem statement in this one and `combinations` problem of my previous post is >>>candidates must be used once<<< and lines `#1` and `2` are here to take care of this. Line `#1` has two components where first `i > 0` and second `candidates[i] == candidates[i-1]`. The second component `candidates[i] == candidates[i-1]` is to take care of duplicates in the `candidates` variable as was instructed in the problem statement. Basically, if the next number in `candidates` is the same as the previous one, it means that it has already been taken care of, so `continue`. The first component takes care of cases like an input `candidates = [1]` with `target = 1` (try to remove this component and submit your solution. You\'ll see what I mean). The rest is similar to the previous [post]()\n\n\n\n================================================================\nFinal note: Please let me know if you found any typo/error/ect. I\'ll try to fix them.
1,729
4Sum
4sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order.
Array,Two Pointers,Sorting
Medium
null
2,536
7
- Approach\n - Brute-force\n - We keep four-pointers `i`, `j`, `k` and `l`. For every quadruplet, we find the sum of `A[i]+A[j]+A[k]+A[l]`\n - If this sum equals the target, we\u2019ve found one of the quadruplets and add it to our data structure and continue with the rest\n - Time Complexity: $O(n^4)$\n - Space Complexity: $O(m)$ where m is the number of quadruplets\n - Better\n - We store the frequency of each element in a HashMap\n - Based on `a + b + c + d = target` we can say that `d = target - (a+b+c)` and based on this we fix 3 elements `a`, `b` and `c` and try to find the `-(a+b+c)` in HashMap\n - Time Complexity: $O(n^3)$\n - Space Complexity: $O(n + m)$ where m is the number of quadruplets\n - Optimal\n - To get the quadruplets in sorted order, we will sort the entire array in the first step and to get the unique quads, we will simply skip the duplicate numbers while moving the pointers\n - Fix 2 pointers `i` and `j` and move 2 pointers `lo` and `hi`\n - Based on `a + b + c + d = target` we can say that `c + d = target - (a+b)` and based on this we fix element as `a` and `b` then find `c` and `d` using two pointers `lo` and `hi` (same as in 3Sum Problem)\n - Time Complexity: $O(n^3)$\n - Space Complexity: $O(m)$ where m is the number of quadruplets\n\n```python\n# Python3\n# Brute-force Solution\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n n = len(nums)\n ans = set()\n for i in range(n-3):\n for j in range(i+1, n-2):\n for k in range(j+1, n-1):\n for l in range(k+1, n):\n if nums[i] + nums[j] + nums[k] + nums[l] == target:\n ans.add(tuple(sorted((nums[i], nums[j], nums[k], nums[l]))))\n \n res = []\n for i in ans:\n res += list(i),\n return res\n```\n\n```python\n# Python3\n# Better Solution\nfrom collections import defaultdict\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n n = len(nums)\n ans = set()\n hmap = defaultdict(int)\n for i in nums:\n hmap[i] += 1\n \n for i in range(n-3):\n hmap[nums[i]] -= 1\n for j in range(i+1, n-2):\n hmap[nums[j]] -= 1\n for k in range(j+1, n-1):\n hmap[nums[k]] -= 1\n rem = target-(nums[i] + nums[j] + nums[k])\n if rem in hmap and hmap[rem] > 0:\n ans.add(tuple(sorted((nums[i], nums[j], nums[k], rem))))\n hmap[nums[k]] += 1\n hmap[nums[j]] += 1\n hmap[nums[i]] += 1\n \n res = []\n for i in ans:\n res += list(i),\n return res\n```\n\n```python\n# Python3\n# Optimal Solution\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n n = len(nums)\n nums.sort()\n res = []\n\n for i in range(n-3):\n # avoid the duplicates while moving i\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n for j in range(i+1, n-2):\n # avoid the duplicates while moving j\n if j > i + 1 and nums[j] == nums[j - 1]:\n continue\n lo = j + 1\n hi = n - 1\n while lo < hi:\n temp = nums[i] + nums[j] + nums[lo] + nums[hi]\n if temp == target:\n res += [nums[i], nums[j], nums[lo], nums[hi]],\n\n # skip duplicates\n while lo < hi and nums[lo] == nums[lo + 1]:\n lo += 1\n lo += 1\n while lo < hi and nums[hi] == nums[hi - 1]:\n hi -= 1\n hi -= 1\n elif temp < target:\n lo += 1\n else:\n hi -= 1\n return res\n```
1,757
4Sum
4sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order.
Array,Two Pointers,Sorting
Medium
null
8,285
14
# Intuition:\nThe problem asks to find all unique quadruplets in the given array whose sum equals the target value. We can use a similar approach as we do for the 3Sum problem. We can sort the array and then use two pointers approach to find the quadruplets whose sum equals the target value.\n\n# Approach:\n\n1. Sort the input array in non-decreasing order.\n2. Traverse the array from 0 to n-3 and use a variable i to keep track of the first element in the quadruplet.\n3. If the current element is the same as the previous element, skip it to avoid duplicates.\n4. Traverse the array from i+1 to n-2 and use a variable j to keep track of the second element in the quadruplet.\n5. If the current element is the same as the previous element, skip it to avoid duplicates.\n6. Use two pointers, left = j+1 and right = n-1, to find the other two elements in the quadruplet whose sum equals the target value.\n7. If the sum of the four elements is less than the target value, increment left pointer.\n8. If the sum of the four elements is greater than the target value, decrement right pointer.\n9. If the sum of the four elements is equal to the target value, add the quadruplet to the result and increment left and decrement right pointers.\n10. Skip duplicate values of left and right pointers to avoid duplicate quadruplets.\n11. Return the result.\n\n# Complexity\n- Time Complexity: O(n^3) where n is the length of the input array. The two outer loops run in O(n^2) time and the inner two-pointer loop runs in O(n) time.\n\n- Space Complexity: O(1) because we are not using any extra space apart from the output array.\n- \n# Similar Question: []()\n---\n# C++\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>> quadruplets;\n int n = nums.size();\n // Sorting the array\n sort(nums.begin(), nums.end());\n for (int i = 0; i < n - 3; i++) {\n // Skip duplicates\n if (i > 0 && nums[i] == nums[i - 1]){\n continue;\n }\n for (int j = i + 1; j < n - 2; j++) {\n // Skip duplicates\n if (j > i + 1 && nums[j] == nums[j - 1]){\n continue;\n }\n int left = j + 1;\n int right = n - 1;\n while (left < right) {\n long long sum = static_cast<long long>(nums[i]) + nums[j] + nums[left] + nums[right];\n if (sum < target) {\n left++;\n } else if (sum > target) {\n right--;\n } else {\n quadruplets.push_back({nums[i], nums[j], nums[left], nums[right]});\n // Skip duplicates\n while (left < right && nums[left] == nums[left + 1]){\n left++;\n }\n while (left < right && nums[right] == nums[right - 1]){\n right--;\n }\n left++;\n right--;\n }\n }\n }\n }\n return quadruplets;\n }\n};\n```\n---\n# Python\n```\nclass Solution(object):\n def fourSum(self, nums, target):\n quadruplets = []\n n = len(nums)\n # Sorting the array\n nums.sort()\n for i in range(n - 3):\n # Skip duplicates\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n for j in range(i + 1, n - 2):\n # Skip duplicates\n if j > i + 1 and nums[j] == nums[j - 1]:\n continue\n left = j + 1\n right = n - 1\n while left < right:\n sum = nums[i] + nums[j] + nums[left] + nums[right]\n if sum < target:\n left += 1\n elif sum > target:\n right -= 1\n else:\n quadruplets.append([nums[i], nums[j], nums[left], nums[right]])\n # Skip duplicates\n while left < right and nums[left] == nums[left + 1]:\n left += 1\n while left < right and nums[right] == nums[right - 1]:\n right -= 1\n left += 1\n right -= 1\n return quadruplets\n\n```\n\n---\n# JAVA\n```\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>> quadruplets = new ArrayList<>();\n int n = nums.length;\n // Sorting the array\n Arrays.sort(nums);\n for (int i = 0; i < n - 3; i++) {\n // Skip duplicates\n if (i > 0 && nums[i] == nums[i - 1]) {\n continue;\n }\n for (int j = i + 1; j < n - 2; j++) {\n // Skip duplicates\n if (j > i + 1 && nums[j] == nums[j - 1]) {\n continue;\n }\n int left = j + 1;\n int right = n - 1;\n while (left < right) {\n long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];\n if (sum < target) {\n left++;\n } else if (sum > target) {\n right--;\n } else {\n quadruplets.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));\n // Skip duplicates\n while (left < right && nums[left] == nums[left + 1]) {\n left++;\n }\n while (left < right && nums[right] == nums[right - 1]) {\n right--;\n }\n left++;\n right--;\n }\n }\n }\n }\n return quadruplets;\n }\n}\n\n```\n\n---\n# JavaScript\n```\nvar fourSum = function(nums, target) {\n nums.sort((a, b) => a - b);\n const quadruplets = [];\n const n = nums.length;\n for (let i = 0; i < n - 3; i++) {\n if (i > 0 && nums[i] === nums[i - 1]) {\n continue;\n }\n for (let j = i + 1; j < n - 2; j++) {\n if (j > i + 1 && nums[j] === nums[j - 1]) {\n continue;\n }\n let left = j + 1;\n let right = n - 1;\n while (left < right) {\n const sum = BigInt(nums[i]) + BigInt(nums[j]) + BigInt(nums[left]) + BigInt(nums[right]);\n if (sum < target) {\n left++;\n } else if (sum > target) {\n right--;\n } else {\n quadruplets.push([nums[i], nums[j], nums[left], nums[right]]);\n while (left < right && nums[left] === nums[left + 1]) {\n left++;\n }\n while (left < right && nums[right] === nums[right - 1]) {\n right--;\n }\n left++;\n right--;\n }\n }\n }\n }\n return quadruplets;\n};\n```\n\n---\n\n# Similar Question: []()
1,771
4Sum
4sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order.
Array,Two Pointers,Sorting
Medium
null
896
7
```\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n res, n = [], len(nums)\n nums.sort()\n for a in range(n):\n for b in range(a+1, n):\n c = b+1; d = n-1\n while c<d:\n sums = nums[a]+nums[b]+nums[c]+nums[d]\n if sums < target:\n c += 1\n elif sums > target:\n d -= 1\n else:\n toappend = [nums[a],nums[b],nums[c],nums[d]]\n if toappend not in res:\n res.append(toappend)\n c +=1\n d-=1\n return res\n```
1,779
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Linked List,Two Pointers
Medium
Maintain two pointers and update one with a delay of n steps.
119,257
1,178
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nWith a singly linked list, the _only_ way to find the end of the list, and thus the **n**\'th node from the end, is to actually iterate all the way to the end. The challenge here is attemping to find the solution in only one pass. A naive approach here might be to store pointers to each node in an array, allowing us to calculate the **n**\'th from the end once we reach the end, but that would take **O(M) extra space**, where **M** is the length of the linked list.\n\nA slightly less naive approach would be to only store only the last **n+1** node pointers in the array. This could be achieved by overwriting the elements of the storage array in circlular fashion as we iterate through the list. This would lower the **space complexity** to **O(N+1)**.\n\nIn order to solve this problem in only one pass and **O(1) extra space**, however, we would need to find a way to _both_ reach the end of the list with one pointer _and also_ reach the **n**\'th node from the end simultaneously with a second pointer.\n\nTo do that, we can simply stagger our two pointers by **n** nodes by giving the first pointer (**fast**) a head start before starting the second pointer (**slow**). Doing this will cause **slow** to reach the **n**\'th node from the end at the same time that **fast** reaches the end.\n\n![Visual 1]()\n\nSince we will need access to the node _before_ the target node in order to remove the target node, we can use **fast.next == null** as our exit condition, rather than **fast == null**, so that we stop one node earlier.\n\nThis will unfortunately cause a problem when **n** is the same as the length of the list, which would make the first node the target node, and thus make it impossible to find the node _before_ the target node. If that\'s the case, however, we can just **return head.next** without needing to stitch together the two sides of the target node.\n\nOtherwise, once we succesfully find the node _before_ the target, we can then stitch it together with the node _after_ the target, and then **return head**.\n\n---\n\n#### ***Implementation:***\n\nThere are only minor differences between the code of all four languages.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **60ms / 40.6MB** (beats 100% / 13%).\n```javascript\nvar removeNthFromEnd = function(head, n) {\n let fast = head, slow = head\n for (let i = 0; i < n; i++) fast = fast.next\n if (!fast) return head.next\n while (fast.next) fast = fast.next, slow = slow.next\n slow.next = slow.next.next\n return head\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **28ms / 13.9MB** (beats 92% / 99%).\n```python\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n fast, slow = head, head\n for _ in range(n): fast = fast.next\n if not fast: return head.next\n while fast.next: fast, slow = fast.next, slow.next\n slow.next = slow.next.next\n return head\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **0ms / 36.5MB** (beats 100% / 97%).\n```java\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode fast = head, slow = head;\n for (int i = 0; i < n; i++) fast = fast.next;\n if (fast == null) return head.next;\n while (fast.next != null) {\n fast = fast.next;\n slow = slow.next;\n }\n slow.next = slow.next.next;\n return head;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 10.6MB** (beats 100% / 93%).\n```c++\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *fast = head, *slow = head;\n for (int i = 0; i < n; i++) fast = fast->next;\n if (!fast) return head->next;\n while (fast->next) fast = fast->next, slow = slow->next;\n slow->next = slow->next->next;\n return head;\n }\n};\n```
1,801
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Linked List,Two Pointers
Medium
Maintain two pointers and update one with a delay of n steps.
29,204
463
This problem is very similar to the **[1721. Swapping Nodes in a Linked List]()** , just that we have to **remove** the kth node from the end instead of swapping it.\n\n\n---\n\n\u2714\uFE0F ***Solution - I (One-Pointer, Two-Pass)***\n\nThis approach is very intuitive and easy to get. \n\n* We just iterate in the first-pass to find the length of the linked list - **`len`**.\n\n* In the next pass, iterate **`len - n - 1`** nodes from start and delete the next node (which would be *`nth`* node from end).\n\n---\n\n**C++**\n```\nListNode* removeNthFromEnd(ListNode* head, int n) {\n\tListNode* iter = head;\n\tint len = 0, i = 1;\n\twhile(iter) iter = iter -> next, len++; // finding the length of linked list\n\tif(len == n) return head -> next; // if head itself is to be deleted, just return head -> next\n\tfor(iter = head; i < len - n; i++) iter = iter -> next; // iterate first len-n nodes\n\titer -> next = iter -> next -> next; // remove the nth node from the end\n\treturn head;\n}\n```\n\n---\n\n**Python**\n```\ndef removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n\tptr, length = head, 0\n\twhile ptr:\n\t\tptr, length = ptr.next, length + 1\n\tif length == n : return head.next\n\tptr = head\n\tfor i in range(1, length - n):\n\t\tptr = ptr.next\n\tptr.next = ptr.next.next\n\treturn head\n```\n\n\n***Time Complexity :*** **`O(N)`**, where, `N` is the number of nodes in the given list. \n***Space Complexity :*** **`O(1)`**, since only constant space is used.\n\n---\n---\n\n\u2714\uFE0F ***Solution (Two-Pointer, One-Pass)***\n\nWe are required to remove the nth node from the end of list. For this, we need to traverse *`N - n`* nodes from the start of the list, where *`N`* is the length of linked list. We can do this in one-pass as follows -\n\n* Let\'s assign two pointers - **`fast`** and **`slow`** to head. We will first iterate for *`n`* nodes from start using the *`fast`* pointer. \n\n* Now, between the *`fast`* and *`slow`* pointers, **there is a gap of `n` nodes**. Now, just Iterate and increment both the pointers till `fast` reaches the last node. The gap between `fast` and `slow` is still of `n` nodes, meaning that **`slow` is nth node from the last node (which currently is `fast`)**.\n\n```\nFor eg. let the list be 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9, and n = 4.\n\n1. 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null\n ^slow ^fast\n |<--gap of n nodes-->|\n \n => Now traverse till fast reaches end\n \n 2. 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null\n ^slow ^fast\n |<--gap of n nodes-->|\n\t\t\t\t\t\t\n\'slow\' is at (n+1)th node from end.\nSo just delete nth node from end by assigning slow -> next as slow -> next -> next (which would remove nth node from end of list).\n```\n\n * Since we have to **delete the nth node from end of list** (And not nth from the last of list!), we just delete the next node to **`slow`** pointer and return the head.\n\n---\n\n**C++**\n```\nListNode* removeNthFromEnd(ListNode* head, int n) {\n\tListNode *fast = head, *slow = head;\n\twhile(n--) fast = fast -> next; // iterate first n nodes using fast\n\tif(!fast) return head -> next; // if fast is already null, it means we have to delete head itself. So, just return next of head\n\twhile(fast -> next) // iterate till fast reaches the last node of list\n\t\tfast = fast -> next, slow = slow -> next; \n\tslow -> next = slow -> next -> next; // remove the nth node from last\n\treturn head;\n}\n```\n\n---\n\n**Python**\n```\ndef removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n\tfast = slow = head\n\tfor i in range(n):\n\t\tfast = fast.next\n\tif not fast: return head.next\n\twhile fast.next:\n\t\tfast, slow = fast.next, slow.next\n\tslow.next = slow.next.next\n\treturn head\n```\n\n\n\n***Time Complexity :*** **`O(N)`**, where, `N` is the number of nodes in the given list. Although, the time complexity is same as above solution, we have reduced the constant factor in it to half.\n***Space Complexity :*** **`O(1)`**, since only constant space is used.\n\n---\n\n**Note :** The Problem only asks us to **remove the node from the linked list and not delete it**. A good question to ask in an interview for this problem would be whether we just need to remove the node from linked list or completely delete it from the memory. Since it has not been stated in this problem if the node is required somewhere else later on, its better to just remove the node from linked list as asked.\n\nIf we want to delete the node altogether, then we can just free its memory and point it to NULL before returning from the function.\n\n\n---\n---\n\n*Best Runtime -*\n\n<table><tr><td><img src= /></td></tr></table>\n\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any questions or mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n---
1,812
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Linked List,Two Pointers
Medium
Maintain two pointers and update one with a delay of n steps.
7,661
16
# Intuition:\nThe problem is to remove the nth node from the end of a linked list. We can find the total number of nodes in the linked list and then traverse the list again to find the nth node from the end. We can then remove the node by updating the pointer of the previous node.\n\n# Approach:\n\n1. Initialize a pointer to the head of the linked list and a count variable to 0.\n2. Traverse the linked list and increment the count for each node until the end of the list is reached.\n3. If the count is equal to n, remove the head node and return the next node as the new head.\n4. Otherwise, initialize the pointer to the head of the linked list again and set n to count - n - 1.\n5. Traverse the linked list again and update the pointer of the previous node to remove the nth node from the end.\n6. Return the head of the linked list.\n\n# Complexity:\n\n- Time Complexity: O(n), where n is the total number of nodes in the linked list. We need to traverse the linked list twice - once to count the total number of nodes and then to find the nth node from the end.\n\n- Space Complexity: O(1), as we are not using any extra space and only using constant space for the pointers and count variable.\n\n---\n# C++\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n if(head==NULL){\n return head;\n }\n ListNode* ptr=head;\n int count = 0;\n while(ptr){\n count++;\n ptr=ptr->next;\n }\n if(count==n){\n head=head->next;\n return head;\n }\n ptr=head;\n n=count-n-1;\n count=0;\n while(ptr){\n if(count==n){\n ptr->next=ptr->next->next;\n }\n count++;\n ptr=ptr->next;\n }\n return head;\n }\n};\n```\n\n---\n# JAVA\n```\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n if (head == null) {\n return head;\n }\n \n ListNode ptr = head;\n int count = 0;\n while (ptr != null) {\n count++;\n ptr = ptr.next;\n }\n \n if (count == n) {\n head = head.next;\n return head;\n }\n \n ptr = head;\n n = count - n - 1;\n count = 0;\n while (ptr != null) {\n if (count == n) {\n ptr.next = ptr.next.next;\n }\n count++;\n ptr = ptr.next;\n }\n \n return head;\n }\n}\n\n```\n---\n# Python\n```\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n if head is None:\n return head\n \n ptr = head\n count = 0\n while ptr is not None:\n count += 1\n ptr = ptr.next\n \n if count == n:\n head = head.next\n return head\n \n ptr = head\n n = count - n - 1\n count = 0\n while ptr is not None:\n if count == n:\n ptr.next = ptr.next.next\n count += 1\n ptr = ptr.next\n \n return head\n\n```\n---\n\n# JavaScript\n```\nvar removeNthFromEnd = function(head, n) {\n if (head === null) {\n return head;\n }\n \n let ptr = head;\n let count = 0;\n while (ptr !== null) {\n count++;\n ptr = ptr.next;\n }\n \n if (count === n) {\n head = head.next;\n return head;\n }\n \n ptr = head;\n n = count - n - 1;\n count = 0;\n while (ptr !== null) {\n if (count === n) {\n ptr.next = ptr.next.next;\n }\n count++;\n ptr = ptr.next;\n }\n \n return head;\n};\n```
1,834
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Linked List,Two Pointers
Medium
Maintain two pointers and update one with a delay of n steps.
96,855
581
**Value-Shifting - AC in 64 ms**\n\nMy first solution is "cheating" a little. Instead of really removing the nth *node*, I remove the nth *value*. I recursively determine the indexes (counting from back), then shift the values for all indexes larger than n, and then always drop the head.\n\n class Solution:\n def removeNthFromEnd(self, head, n):\n def index(node):\n if not node:\n return 0\n i = index(node.next) + 1\n if i > n:\n node.next.val = node.val\n return i\n index(head)\n return head.next\n\n---\n\n**Index and Remove - AC in 56 ms**\n\nIn this solution I recursively determine the indexes again, but this time my helper function removes the nth node. It returns two values. The index, as in my first solution, and the possibly changed head of the remaining list.\n\n class Solution:\n def removeNthFromEnd(self, head, n):\n def remove(head):\n if not head:\n return 0, head\n i, head.next = remove(head.next)\n return i+1, (head, head.next)[i+1 == n]\n return remove(head)[1]\n\n---\n\n**n ahead - AC in 48 ms**\n\nThe standard solution, but without a dummy extra node. Instead, I simply handle the special case of removing the head right after the fast cursor got its head start.\n\n class Solution:\n def removeNthFromEnd(self, head, n):\n fast = slow = head\n for _ in range(n):\n fast = fast.next\n if not fast:\n return head.next\n while fast.next:\n fast = fast.next\n slow = slow.next\n slow.next = slow.next.next\n return head
1,837
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Linked List,Two Pointers
Medium
Maintain two pointers and update one with a delay of n steps.
18,226
187
Please upvote once you get this :)\n```\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n fast = head\n slow = head\n # advance fast to nth position\n for i in range(n):\n fast = fast.next\n \n if not fast:\n return head.next\n # then advance both fast and slow now they are nth postions apart\n # when fast gets to None, slow will be just before the item to be deleted\n while fast.next:\n slow = slow.next\n fast = fast.next\n # delete the node\n slow.next = slow.next.next\n return head\n```
1,845
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Linked List,Two Pointers
Medium
Maintain two pointers and update one with a delay of n steps.
1,465
9
# Solution no. 01\nThe first solution helps you understand the basics with simple steps. \n\n# Intuition\n\nTo determine the node to remove, which is n positions from the end, we need to figure out how many positions we should move from the front to reach the desired node. By counting the total number of nodes in the linked list, we gain this insight and can then adjust the connections accordingly to remove the targeted node from the end.\n\n# Approach\n1. Count the total number of nodes in the linked list by traversing it with a curr pointer.\n1. Calculate the position to move from the front to reach the node n positions from the end.\n1. Reset the count and curr to traverse the list again.\n1. If the node to be removed is the first node, return head.next.\n1. Traverse the list while keeping track of the count.\n1. When the count matches the calculated position before the node to be removed, update the connection to skip the node.\n1. Exit the loop after performing the removal.\n1. Return the updated head.\n\n# Complexity\n- Time complexity:\nWe traverse the linked list twice, so the time complexity is O(n), where n is the number of nodes in the list.\n\n- Space complexity:\nWe only use a few variables, so the space complexity is O(1).\n\n# Code\n```\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n count = 0\n curr = head\n while curr:\n count += 1\n curr = curr.next\n\n check = count - n - 1\n count = 0\n curr = head\n\n # Removing the first node\n if check == -1: \n return head.next\n\n while curr:\n if count == check:\n curr.next = curr.next.next\n # As the removal is done, Exit the loop\n break \n curr = curr.next\n count += 1\n\n return head\n\n```\n\n\n---\n\n# Solution no. 02\n\n# Intuition\nIn our first approach we counted the total number of nodes in the linked list and then identify the n-th node from the end by its position from the beginning. While this counting approach could work, it involves traversing the list twice: once to count the nodes and once to find the node to remove. This double traversal can be inefficient, especially for large lists.\n\nA more efficient approach comes from recognizing that we don\'t really need to know the total number of nodes in the list to solve this problem. Instead, we can utilize two pointers to maintain a specific gap between them as they traverse the list. This gap will be the key to identifying the n-th node from the end.\n\n# Approach\n1. We\'ll use two pointers, first and second, initialized to a dummy node at the beginning of the linked list. The goal is to maintain a gap of n+1 nodes between the two pointers as we traverse the list.\n\n1. Move the first pointer n+1 steps ahead, creating a gap of n nodes between first and second.\n\n1. Now, move both first and second pointers one step at a time until the first pointer reaches the end of the list. This ensures that the gap between the two pointers remains constant at n nodes.\n\n1. When first reaches the end, the second pointer will be pointing to the node right before the node we want to remove (n-th node from the end).\n\n1. Update the second.next pointer to skip the n-th node, effectively removing it from the list.\n\n# Complexity\n- Time complexity:\n The solution involves a single pass through the linked list, so the time complexity is **O(N)**, where N is the number of nodes in the linked list.\n\n- Space complexity:\nWe are using a constant amount of extra space to store the dummy, first, and second pointers, so the space complexity is **O(1)**.\n\n# Code\n```\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n dummy = ListNode(0)\n dummy.next = head\n \n first = dummy\n second = dummy\n \n # Advance first pointer so that the gap between first and second is n+1 nodes apart\n for i in range(n+1):\n first = first.next\n \n # Move first to the end, maintaining the gap\n while first:\n first = first.next\n second = second.next\n \n # Remove the nth node from the end\n second.next = second.next.next\n \n return dummy.next \n\n```\n\n
1,867
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Linked List,Two Pointers
Medium
Maintain two pointers and update one with a delay of n steps.
949
9
```\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n if head.next is None:\n return None\n \n size=0\n curr= head\n while curr!= None:\n curr= curr.next\n size+=1\n if n== size:\n return head.next\n \n indexToSearch= size-n\n prev= head\n i=1\n while i< indexToSearch:\n prev= prev.next\n i+=1\n prev.next= prev.next.next\n return head\n```\n\n**UPVOTE** *is the best encouragement for me... Thank you*\uD83D\uDE01
1,870
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
180,259
1,264
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to determine if the given string of brackets is valid or not. We can use a stack data structure to keep track of opening brackets encountered and check if they match with the corresponding closing brackets.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere is the step-by-step approach of the algorithm:\n1. Initialize an empty stack.\n\n2. Traverse the input string character by character.\n\n3. If the current character is an opening bracket (i.e., \'(\', \'{\', \'[\'), push it onto the stack.\n\n4. If the current character is a closing bracket (i.e., \')\', \'}\', \']\'), check if the stack is empty. If it is empty, return false, because the closing bracket does not have a corresponding opening bracket. Otherwise, pop the top element from the stack and check if it matches the current closing bracket. If it does not match, return false, because the brackets are not valid.\n\n5. After traversing the entire input string, if the stack is empty, return true, because all opening brackets have been matched with their corresponding closing brackets. Otherwise, return false, because some opening brackets have not been matched with their corresponding closing brackets.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the solution is $$O(n)$$, where n is the length of the input string. This is because we traverse the string once and perform constant time operations for each character.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of the solution is $$O(n)$$, where n is the length of the input string. This is because the worst-case scenario is when all opening brackets are present in the string and the stack will have to store them all.\n\n![image.png]()\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n```\n\n# Code\n```java []\nclass Solution {\n public boolean isValid(String s) {\n Stack<Character> stack = new Stack<Character>(); // create an empty stack\n for (char c : s.toCharArray()) { // loop through each character in the string\n if (c == \'(\') // if the character is an opening parenthesis\n stack.push(\')\'); // push the corresponding closing parenthesis onto the stack\n else if (c == \'{\') // if the character is an opening brace\n stack.push(\'}\'); // push the corresponding closing brace onto the stack\n else if (c == \'[\') // if the character is an opening bracket\n stack.push(\']\'); // push the corresponding closing bracket onto the stack\n else if (stack.isEmpty() || stack.pop() != c) // if the character is a closing bracket\n // if the stack is empty (i.e., there is no matching opening bracket) or the top of the stack\n // does not match the closing bracket, the string is not valid, so return false\n return false;\n }\n // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets,\n // so the string is valid, otherwise, there are unmatched opening brackets, so return false\n return stack.isEmpty();\n }\n}\n\n```\n```java []\nclass Solution {\n public boolean isValid(String s) {\n // Create an empty stack to keep track of opening brackets\n Stack<Character> stack = new Stack<Character>();\n \n // Loop through every character in the string\n for (char c : s.toCharArray()) {\n // If the character is an opening bracket, push it onto the stack\n if (c == \'(\' || c == \'[\' || c == \'{\') {\n stack.push(c);\n } else { // If the character is a closing bracket\n // If the stack is empty, there is no matching opening bracket, so return false\n if (stack.isEmpty()) {\n return false;\n }\n // Otherwise, get the top of the stack and check if it\'s the matching opening bracket\n char top = stack.peek();\n if ((c == \')\' && top == \'(\') || (c == \']\' && top == \'[\') || (c == \'}\' && top == \'{\')) {\n // If it is, pop the opening bracket from the stack\n stack.pop();\n } else { // Otherwise, the brackets don\'t match, so return false\n return false;\n }\n }\n }\n // If the stack is empty, all opening brackets have been closed, so return true\n // Otherwise, there are unmatched opening brackets, so return false\n return stack.isEmpty();\n }\n}\n\n```\n```python []\nclass Solution(object):\n def isValid(self, s):\n stack = [] # create an empty stack to store opening brackets\n for c in s: # loop through each character in the string\n if c in \'([{\': # if the character is an opening bracket\n stack.append(c) # push it onto the stack\n else: # if the character is a closing bracket\n if not stack or \\\n (c == \')\' and stack[-1] != \'(\') or \\\n (c == \'}\' and stack[-1] != \'{\') or \\\n (c == \']\' and stack[-1] != \'[\'):\n return False # the string is not valid, so return false\n stack.pop() # otherwise, pop the opening bracket from the stack\n return not stack # if the stack is empty, all opening brackets have been matched with their corresponding closing brackets,\n # so the string is valid, otherwise, there are unmatched opening brackets, so return false\n```\n```c++ []\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> st; // create an empty stack to store opening brackets\n for (char c : s) { // loop through each character in the string\n if (c == \'(\' || c == \'{\' || c == \'[\') { // if the character is an opening bracket\n st.push(c); // push it onto the stack\n } else { // if the character is a closing bracket\n if (st.empty() || // if the stack is empty or \n (c == \')\' && st.top() != \'(\') || // the closing bracket doesn\'t match the corresponding opening bracket at the top of the stack\n (c == \'}\' && st.top() != \'{\') ||\n (c == \']\' && st.top() != \'[\')) {\n return false; // the string is not valid, so return false\n }\n st.pop(); // otherwise, pop the opening bracket from the stack\n }\n }\n return st.empty(); // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets,\n // so the string is valid, otherwise, there are unmatched opening brackets, so return false\n }\n};\n```\n\n```javascript []\n/**\n * @param {string} s\n * @return {boolean}\n */\nvar isValid = function(s) {\n let stack = []; // create an empty stack to store opening brackets\n for (let c of s) { // loop through each character in the string\n if (c === \'(\' || c === \'{\' || c === \'[\') { // if the character is an opening bracket\n stack.push(c); // push it onto the stack\n } else { // if the character is a closing bracket\n if (!stack.length || // if the stack is empty or \n (c === \')\' && stack[stack.length - 1] !== \'(\') || // the closing bracket doesn\'t match the corresponding opening bracket at the top of the stack\n (c === \'}\' && stack[stack.length - 1] !== \'{\') ||\n (c === \']\' && stack[stack.length - 1] !== \'[\')) {\n return false; // the string is not valid, so return false\n }\n stack.pop(); // otherwise, pop the opening bracket from the stack\n }\n }\n return !stack.length; // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets,\n // so the string is valid, otherwise, there are unmatched opening brackets, so return false\n};\n\n```\n\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n```
1,900
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
1,772
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(object):\n def isValid(self, s):\n stack = [] # Initialize an empty list to represent the stack\n\n if len(s) % 2 != 0:\n return False\n else:\n left = [\'(\', \'[\', \'{\']\n right = [\')\', \']\', \'}\']\n\n for char in s:\n if char in left:\n stack.append(char)\n elif char in right:\n if not stack: # Check if the stack is empty before \n return False\n top = stack.pop()\n if char == \')\':\n if top != \'(\':\n return False\n elif char == \'}\':\n if top != \'{\':\n return False\n elif char == \']\':\n if top != \'[\':\n return False\n return not stack # Return True if the stack is empty, False otherwise\n```
1,901
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
113,953
385
An input string is valid if:\n1. Open brackets must be closed by the same type of brackets.\n2. Open brackets must be closed in the correct order.\n\n# **C++ Solution:**\nRuntime: 0 ms, faster than 100.00% of C++ online submissions for Valid Parentheses.\n```\nclass Solution {\npublic:\n bool isValid(string s) {\n // Initialize a stack and a index idx = 0...\n stack<char> stack;\n int idx = 0;\n // If the string is empty, return true...\n if(s.size() == 0){\n return true;\n }\n // Create a loop to check parentheses...\n while(idx < s.size()){\n // If it contains the below parentheses, push the char to stack...\n if( s[idx] == \'(\' || s[idx] == \'[\' || s[idx] == \'{\' ){\n stack.push(s[idx]);\n }\n // If the current char is a closing brace provided, pop the top element...\n // Stack is not empty...\n else if ( (s[idx] == \')\' && !stack.empty() && stack.top() == \'(\') ||\n (s[idx] == \'}\' && !stack.empty() && stack.top() == \'{\') ||\n (s[idx] == \']\' && !stack.empty() && stack.top() == \'[\')\n ){\n stack.pop();\n }\n else {\n return false; // If The string is not a valid parenthesis...\n }\n idx++; // Increase the index...\n }\n // If stack.empty(), return true...\n if(stack.empty()) {\n return true;\n }\n return false;\n }\n};\n```\n\n# **Java Solution (Using Hashmap):**\n```\nclass Solution {\n public boolean isValid(String s) {\n // Create hashmap to store the pairs...\n HashMap<Character, Character> Hmap = new HashMap<Character, Character>();\n Hmap.put(\')\',\'(\');\n Hmap.put(\'}\',\'{\');\n Hmap.put(\']\',\'[\');\n // Create stack data structure...\n Stack<Character> stack = new Stack<Character>();\n // Traverse each charater in input string...\n for (int idx = 0; idx < s.length(); idx++){\n // If open parentheses are present, push it to stack...\n if (s.charAt(idx) == \'(\' || s.charAt(idx) == \'{\' || s.charAt(idx) == \'[\') {\n stack.push(s.charAt(idx));\n continue;\n }\n // If the character is closing parentheses, check that the same type opening parentheses is being pushed to the stack or not...\n // If not, we need to return false...\n if (stack.size() == 0 || Hmap.get(s.charAt(idx)) != stack.pop()) {\n return false;\n }\n }\n // If the stack is empty, return true...\n if (stack.size() == 0) {\n return true;\n }\n return false;\n }\n}\n```\n\n# **Python Solution:**\n```\nclass Solution(object):\n def isValid(self, s):\n # Create a pair of opening and closing parrenthesis...\n opcl = dict((\'()\', \'[]\', \'{}\'))\n # Create stack data structure...\n stack = []\n # Traverse each charater in input string...\n for idx in s:\n # If open parentheses are present, append it to stack...\n if idx in \'([{\':\n stack.append(idx)\n # If the character is closing parentheses, check that the same type opening parentheses is being pushed to the stack or not...\n # If not, we need to return false...\n elif len(stack) == 0 or idx != opcl[stack.pop()]:\n return False\n # At last, we check if the stack is empty or not...\n # If the stack is empty it means every opened parenthesis is being closed and we can return true, otherwise we return false...\n return len(stack) == 0\n```\n \n# **JavaScript Solution:**\n```\nvar isValid = function(s) {\n // Initialize stack to store the closing brackets expected...\n let stack = [];\n // Traverse each charater in input string...\n for (let idx = 0; idx < s.length; idx++) {\n // If open parentheses are present, push it to stack...\n if (s[idx] == \'{\') {\n stack.push(\'}\');\n } else if (s[idx] == \'[\') {\n stack.push(\']\');\n } else if (s[idx] == \'(\') {\n stack.push(\')\');\n }\n // If a close bracket is found, check that it matches the last stored open bracket\n else if (stack.pop() !== s[idx]) {\n return false;\n }\n }\n return !stack.length;\n};\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def isValid(self, s: str) -> bool:\n # Create a pair of opening and closing parrenthesis...\n opcl = dict((\'()\', \'[]\', \'{}\'))\n # Create stack data structure...\n stack = []\n # Traverse each charater in input string...\n for idx in s:\n # If open parentheses are present, append it to stack...\n if idx in \'([{\':\n stack.append(idx)\n # If the character is closing parentheses, check that the same type opening parentheses is being pushed to the stack or not...\n # If not, we need to return false...\n elif len(stack) == 0 or idx != opcl[stack.pop()]:\n return False\n # At last, we check if the stack is empty or not...\n # If the stack is empty it means every opened parenthesis is being closed and we can return true, otherwise we return false...\n return len(stack) == 0\n```\n**I am working hard for you guys...\nPlease upvote if you find any help with this code...**
1,919
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
3,254
28
\n\nSince the **last** bracket that is opened must also be the **first** one to be closed, it makes sense to use a data structure that uses the **Last In, First Out** (LIFO) principle. Therefore, a **stack** is a good choice here.\n\nIf a bracket is an *opening* bracet, we\'ll just push it on to the stack. If it\'s a *closing* bracket, then we\'ll use the `pairs` dictionary to check if it\'s the correct type of bracket (first pop the last opening bracket encountered, find the corresponding closing bracket, and compare it with the current bracket in the loop). If the wrong type of closing bracket is found, then we can exit early and return False.\n\nIf we make it all the way to the end and all open brackets have been closed, then the stack should be empty. This is why we `return len(stack) == 0` at the end. This will return `True` if the stack is empty, and `False` if it\'s not.\n\n```\nclass Solution(object):\n def isValid(self, s):\n stack = [] # only use append and pop\n pairs = {\n \'(\': \')\',\n \'{\': \'}\',\n \'[\': \']\'\n }\n for bracket in s:\n if bracket in pairs:\n stack.append(bracket)\n elif len(stack) == 0 or bracket != pairs[stack.pop()]:\n return False\n\n return len(stack) == 0\n\n```
1,921
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
957
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code checks whether a given string containing only parentheses, brackets, and curly braces is valid in terms of their arrangement. A valid string should have each opening bracket matched with its corresponding closing bracket in the correct order.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code uses a stack to keep track of the opening brackets encountered so far. When a closing bracket is encountered, it is checked if it matches the last opening bracket. If it does, the last opening bracket is popped from the stack. If there is a mismatch or if the stack is empty when a closing bracket is encountered, the string is considered invalid.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(n), where n is the length of the input string. In the worst case, the algorithm iterates through each character in the string once.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n), where n is the length of the input string. In the worst case, the stack can grow to the size of the input string when all characters are opening brackets.\n# Code\n```\nclass Solution:\n def isValid(self, s: str) -> bool:\n # Dictionary to store the mapping of opening and closing brackets\n brackets = {\'(\':\')\', \'{\':\'}\', \'[\':\']\'}\n \n # Stack to keep track of opening brackets\n stack = []\n \n # Iterate through each character in the input string\n for i in s:\n # If the character is an opening bracket, push it onto the stack\n if i in brackets:\n stack.append(i)\n else:\n # If the stack is empty or the current closing bracket doesn\'t match\n # the corresponding opening bracket, return False\n if len(stack) == 0 or i != brackets[stack.pop()]:\n return False\n \n # Check if there are any remaining opening brackets in the stack\n return len(stack) == 0\n\n```
1,946
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
35,599
114
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isValid(self, s: str) -> bool:\n while \'()\' in s or \'[]\'in s or \'{}\' in s:\n s = s.replace(\'()\',\'\').replace(\'[]\',\'\').replace(\'{}\',\'\')\n return False if len(s) !=0 else True\n```
1,952
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
61,965
434
```\nclass Solution(object):\n\tdef isValid(self, s):\n """\n :type s: str\n :rtype: bool\n """\n d = {\'(\':\')\', \'{\':\'}\',\'[\':\']\'}\n stack = []\n for i in s:\n if i in d: # 1\n stack.append(i)\n elif len(stack) == 0 or d[stack.pop()] != i: # 2\n return False\n return len(stack) == 0 # 3\n\t\n# 1. if it\'s the left bracket then we append it to the stack\n# 2. else if it\'s the right bracket and the stack is empty(meaning no matching left bracket), or the left bracket doesn\'t match\n# 3. finally check if the stack still contains unmatched left bracket\n```
1,967
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
2,870
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use a stack to maintain the order of open brackets encountered.\nWhen a closing bracket is encountered, we check if it matches the last encountered open bracket.\nIf the brackets are balanced and correctly ordered, the stack should be empty at the end.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used here is to iterate through the input string s character by character. We maintain a stack to keep track of open brackets encountered. When we encounter an open bracket (\'(\', \'{\', or \'[\'), we push it onto the stack. When we encounter a closing bracket (\')\', \'}\', or \']\'), we check if there is a matching open bracket at the top of the stack. If not, it means the brackets are not balanced, and we return false. If there is a matching open bracket, we pop it from the stack.\n\nAt the end of the loop, if the stack is empty, it indicates that all open brackets have been closed properly, and we return true. Otherwise, if there are unmatched open brackets left in the stack, we return false.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(n), where n is the length of the input string s. This is because we iterate through the string once, and each character operation takes constant time.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n) as well, where n is the length of the input string s. In the worst case, all characters in the string could be open brackets, and they would be pushed onto the stack.\n\n---\n\n\n# \uD83D\uDCA1"If you have come this far, I would like to kindly request your support by upvoting this solution, thus enabling it to reach a broader audience."\u2763\uFE0F\uD83D\uDCA1\n\n---\n\n\n# Code\n\n```C++ []\n#include <stack>\n#include <string>\n\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> brackets;\n \n for (char c : s) {\n if (c == \'(\' || c == \'{\' || c == \'[\') {\n brackets.push(c);\n } else {\n if (brackets.empty()) {\n return false; // There\'s no matching open bracket.\n }\n \n char openBracket = brackets.top();\n brackets.pop();\n \n if ((c == \')\' && openBracket != \'(\') ||\n (c == \'}\' && openBracket != \'{\') ||\n (c == \']\' && openBracket != \'[\')) {\n return false; // Mismatched closing bracket.\n }\n }\n }\n \n return brackets.empty(); // All open brackets should be closed.\n }\n};\n```\n```Java []\nimport java.util.Stack;\n\nclass Solution {\n public boolean isValid(String s) {\n Stack<Character> brackets = new Stack<>();\n \n for (char c : s.toCharArray()) {\n if (c == \'(\' || c == \'{\' || c == \'[\') {\n brackets.push(c);\n } else {\n if (brackets.isEmpty()) {\n return false; // There\'s no matching open bracket.\n }\n \n char openBracket = brackets.pop();\n \n if ((c == \')\' && openBracket != \'(\') ||\n (c == \'}\' && openBracket != \'{\') ||\n (c == \']\' && openBracket != \'[\')) {\n return false; // Mismatched closing bracket.\n }\n }\n }\n \n return brackets.isEmpty(); // All open brackets should be closed.\n }\n}\n\n```\n```Python []\nclass Solution:\n def isValid(self, s: str) -> bool:\n brackets = []\n \n for c in s:\n if c in \'({[\':\n brackets.append(c)\n else:\n if not brackets:\n return False # There\'s no matching open bracket.\n \n open_bracket = brackets.pop()\n \n if (c == \')\' and open_bracket != \'(\') or (c == \'}\' and open_bracket != \'{\') or (c == \']\' and open_bracket != \'[\'):\n return False # Mismatched closing bracket.\n \n return not brackets # All open brackets should be closed.\n\n```\n```Javascript []\nvar isValid = function(s) {\n const brackets = [];\n \n for (let c of s) {\n if (c === \'(\' || c === \'{\' || c === \'[\') {\n brackets.push(c);\n } else {\n if (brackets.length === 0) {\n return false; // There\'s no matching open bracket.\n }\n \n const openBracket = brackets.pop();\n \n if ((c === \')\' && openBracket !== \'(\') || (c === \'}\' && openBracket !== \'{\') || (c === \']\' && openBracket !== \'[\')) {\n return false; // Mismatched closing bracket.\n }\n }\n }\n \n return brackets.length === 0; // All open brackets should be closed.\n};\n\n```\n```Ruby []\ndef is_valid(s)\n brackets = []\n \n s.chars.each do |c|\n if c == \'(\' || c == \'{\' || c == \'[\'\n brackets.push(c)\n else\n if brackets.empty?\n return false # There\'s no matching open bracket.\n end\n \n open_bracket = brackets.pop\n \n if (c == \')\' && open_bracket != \'(\') || (c == \'}\' && open_bracket != \'{\') || (c == \']\' && open_bracket != \'[\')\n return false # Mismatched closing bracket.\n end\n end\n end\n \n brackets.empty? # All open brackets should be closed.\nend\n\n```
1,988
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
9,581
12
\n# Code\n```\nclass Solution:\n def isValid(self, s: str) -> bool:\n ack = []\n lookfor = {\')\':\'(\', \'}\':\'{\', \']\':\'[\'}\n\n for p in s:\n if p in lookfor.values():\n ack.append(p)\n elif ack and lookfor[p] == ack[-1]:\n ack.pop()\n else:\n return False\n\n return ack == []\n```
1,994
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
261,655
1,078
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nFor simplicity, we create a dummy node to which we attach nodes from lists. We iterate over lists using two-pointers and build up a resulting list so that values are monotonically increased.\n\nTime: **O(n)**\nSpace: **O(1)**\n\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n cur = dummy = ListNode()\n while list1 and list2: \n if list1.val < list2.val:\n cur.next = list1\n list1, cur = list1.next, list1\n else:\n cur.next = list2\n list2, cur = list2.next, list2\n \n if list1 or list2:\n cur.next = list1 if list1 else list2\n \n return dummy.next\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
2,001
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
15,662
125
\n\nWe\'ll create a starting node called `head` and use a pointer called `current` to traverse the two lists. At each iteration of the loop, we compare the values of the nodes at list1 and list2, and point `current.next` to the <i>smaller</i> node. Then we advance the pointers and repeat until one of the list pointers reaches the end of the list.\n\nAt this point, there\'s no need to iterate through the rest of the other list because we know that it\'s still in sorted order. So `current.next = list1 or list2` points current.next to the list that still has nodes left. The last step is just to return `head.next`, since head was just a placeholder node and the actual list starts at `head.next`.\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def mergeTwoLists(self, list1, list2):\n head = ListNode()\n current = head\n while list1 and list2:\n if list1.val < list2.val:\n current.next = list1\n list1 = list1.next\n else:\n current.next = list2\n list2 = list2.next\n current = current.next\n\n current.next = list1 or list2\n return head.next\n```
2,004
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
39,656
484
[Linkedlists]() can be confusing especially if you\'ve recently started to code but (I think) once you understand it fully, it should not be that difficult. \n\nFor this problem, I\'m going to explain several ways of solving it **BUT** I want to make something clear. Something that you\'ve seen a lot of times in the posts on this website but probably haven\'t fully understood. `dummy` variable! It has been used significantly in the solutions of this problem and not well explained for a newbie level coder! The idea is we\'re dealing with `pointers` that point to a memory location! Think of it this way! You want to find gold that is hidden somewhere. Someone has put a set of clues in a sequence! Meaning, if you find the first clue and solve the problem hidden in the clue, you will get to the second clue! Solving the hidden problem of second clue will get you to the thrid clue, and so on! If you keep solving, you\'ll get to the gold! `dummy` helps you to find the first clue!!!! \n\nThroughout the solution below, you\'ll be asking yourself why `dummy` is not changing and we eventually return `dummy.next`???? It doesn\'t make sense, right? However, if you think that `dummy` is pointing to the start and there is another variable (`temp`) that makes the linkes from node to node, you\'ll have a better filling! \nSimilar to the gold example if I tell you the first clue is at location X, then, you can solve clues sequentially (because of course you\'re smart) and bingo! you find the gold! Watch [this](). \n\nThis video shows why we need the `dummy`! Since we\'re traversing using `temp` but once `temp` gets to the tail of the sorted merged linkedlist, there\'s no way back to the start of the list to return as a result! So `dummy` to the rescue! it does not get changed throughout the list traversals `temp` is doing! So, `dummy` makes sure we don\'t loose the head of the thread (result list). Does this make sense? Alright! Enough with `dummy`! \n\nI think if you get this, the first solution feels natural! Now, watch [this](). You got the idea?? Nice! \n\n\nFirst you initialize `dummy` and `temp`. One is sitting at the start of the linkedlist and the other (`temp`) is going to move forward find which value should be added to the list. Note that it\'s initialized with a value `0` but it can be anything! You initialize it with your value of choice! Doesn\'t matter since we\'re going to finally return `dummy.next` which disregards `0` that we used to start the linkedlist. Line `#1` makes sure none of the `l1` and `l2` are empty! If one of them is empty, we should return the other! If both are nonempty, we check `val` of each of them to add the smaller one to the result linkedlist! In line `#2`, `l1.val` is smaller and we want to add it to the list. How? We use `temp` POINTER (it\'s pointer, remember that!). Since we initialized `temp` to have value `0` at first node, we use `temp.next` to point `0` to the next value we\'re going to add to the list `l1.val` (line `#3`). Once we do that, we update `l1` to go to the next node of `l1`. If the `if` statement of line `#2` doesn\'t work, we do similar stuff with `l2`. And finally, if the length of `l1` and `l2` are not the same, we\'re going to the end of one of them at some point! Line `#5` adds whatever left from whatever linkedlist to the `temp.next` (check the above video for a great explanation of this part). Note that both linkedlists were sorted initially. Also, this line takes care of when one of the linkedlists are empty. Finally, we return `dummy.next` since `dummy` is pointing to `0` and `next` to zero is what we\'ve added throughout the process. \n\n```\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: \n dummy = temp = ListNode(0)\n while l1 != None and l2 != None: #1\n\n if l1.val < l2.val: #2\n temp.next = l1 #3\n l1 = l1.next #4\n else: \n temp.next = l2\n l2 = l2.next\n temp = temp.next\n temp.next = l1 or l2 #5\n return dummy.next #6\n```\n\n\nAnother way of solving is problem is by doing recursion. This is from [here]((iteratively-recursively-iteratively-in-place)). The first check is obvious! If one of them is empty, return the other one! Similar to line `#5` of previous solution. Here, we have two cases, whatever list has the smaller first element (equal elements also satisfies line `#1`), will be returned at the end. In the example `l1 = [1,2,4], l2 = [1,3,4]`, we go in the `if` statement of line `#1` first, this means that the first element of `l1` doesn\'t get changed! Then, we move the pointer to the second element of `l1` by calling the function again but with `l1.next` and `l2` as input! This round of call, goes to line `#2` because now we have element `1` from `l2` versus `2` from `l1`. Now, basically, `l2` gets connected to the tail of `l1`. We keep moving forward by switching between `l1` and `l2` until the last element. Sorry if it\'s not clear enough! I\'m not a fan of recursion for such a problems! But, let me know which part it\'s hard to understand, I\'ll try to explain better! \n\n```\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: \n if not l1 or not l2:\n return l1 or l2\n \n if l1.val <= l2.val: #1\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\n else: #2\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n===============================================================\nFinal note: Please let me know if you want me to explain anything in more detail. \n
2,009
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
821
7
# Intuition\n<!-- Your intuition or thoughts about solving the problem -->\nMy intuition is to merge two sorted linked lists into a single sorted linked list while keeping track of the current nodes in both input lists.\n\n# Approach\n<!-- Describe your approach to solving the problem -->\n1. Initialize a new linked list named `merged`.\n2. Initialize a temporary node `temp` pointing to `merged`.\n3. While both `l1` and `l2` are not empty:\n - Compare the values of the current nodes in `l1` and `l2`.\n - If `l1.val` is less than `l2.val`, set `temp.next` to `l1` and move `l1` to the next node.\n - If `l1.val` is greater than or equal to `l2.val`, set `temp.next` to `l2` and move `l2` to the next node.\n - Move `temp` to the next node.\n4. After the loop, if there are remaining nodes in `l1`, append them to `temp.next`.\n5. If there are remaining nodes in `l2`, append them to `temp.next`.\n6. Return the `next` node of `merged` as the merged linked list.\n\n# Complexity\n- Time complexity:\n - The while loop iterates through both linked lists, and each step involves constant-time operations.\n - The time complexity is O(n), where n is the total number of nodes in the two linked lists.\n\n- Space complexity:\n - Your code uses a constant amount of extra space for variables (`merged` and `temp`), and the space complexity is O(1).\n\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n merged = ListNode()\n temp = merged\n\n while l1 and l2 :\n if l1.val < l2.val :\n temp.next = l1\n l1 = l1.next\n else :\n temp.next = l2\n l2 = l2.next\n\n temp = temp.next\n\n if l1:\n temp.next = l1\n else :\n temp.next = l2\n\n return merged.next \n\n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg]()\n
2,010
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
4,075
14
\n\n# Single Linked List----->Time : O(N)\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n out=dummy=ListNode()\n while list1 and list2:\n if list1.val<list2.val:\n out.next=list1\n list1=list1.next\n else:\n out.next=list2\n list2=list2.next\n out=out.next\n if list1:\n out.next=list1\n list1=list1.next\n if list2:\n out.next=list2\n list2=list2.next\n return dummy.next\n\n```\n# please upvote me it would encourage me alot\n
2,011
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
174,293
977
\n \n # iteratively\n def mergeTwoLists1(self, l1, l2):\n dummy = cur = ListNode(0)\n while l1 and l2:\n if l1.val < l2.val:\n cur.next = l1\n l1 = l1.next\n else:\n cur.next = l2\n l2 = l2.next\n cur = cur.next\n cur.next = l1 or l2\n return dummy.next\n \n # recursively \n def mergeTwoLists2(self, l1, l2):\n if not l1 or not l2:\n return l1 or l2\n if l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\n else:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2\n \n # in-place, iteratively \n def mergeTwoLists(self, l1, l2):\n if None in (l1, l2):\n return l1 or l2\n dummy = cur = ListNode(0)\n dummy.next = l1\n while l1 and l2:\n if l1.val < l2.val:\n l1 = l1.next\n else:\n nxt = cur.next\n cur.next = l2\n tmp = l2.next\n l2.next = nxt\n l2 = tmp\n cur = cur.next\n cur.next = l1 or l2\n return dummy.next
2,012
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
29,477
97
**IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE**\n\nVisit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: \n\n**Solution:**\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n newHead = dummyHead = ListNode()\n while list1 and list2:\n if list1.val < list2.val:\n dummyHead.next = list1\n list1 = list1.next\n else:\n dummyHead.next = list2\n list2 = list2.next\n dummyHead = dummyHead.next\n \n if list1:\n dummyHead.next = list1\n if list2:\n dummyHead.next = list2\n return newHead.next\n```\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.**
2,021
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
17,618
41
# Intuition:\nThe problem requires us to merge two sorted linked lists into a new sorted linked list. We can achieve this by comparing the values of the head nodes of the two linked lists and adding the smaller one to our new merged linked list. We can repeat this process by advancing the pointer of the smaller element and comparing it with the other linked list\'s head node\'s value, and we continue this process until we exhaust all the nodes in both lists. This way, we can obtain a new linked list containing all the elements of both linked lists in a sorted order.\n\n# Approach:\n\n- **Recursive Approach:**\nThe recursive approach is based on the idea that we compare the values of the first nodes of the two lists, and whichever has the smaller value, we add that node to our merged linked list and call the same function recursively with the next node of that list and the other list\'s current node. We repeat this process until one of the lists exhausts, and we return the merged list.\n\n- **Iterative Approach:**\nThe iterative approach is based on the same idea as the recursive approach. Here, we maintain three pointers: one for the merged linked list\'s head, one for the current node of the merged list, and one for the current node of each of the two input linked lists. We compare the two lists\' head nodes and add the smaller one to our merged linked list and advance the pointer of that list. We continue this process until we exhaust one of the input lists, and then we add the remaining nodes of the other list to our merged linked list.\n\n# Complexity:\n\n- Time complexity: Both approaches take O(n+m) time, where n and m are the sizes of the two linked lists because we iterate through all the nodes of both linked lists at most once.\n\n- Space complexity: Recursive approach has a space complexity of O(n+m) due to the recursive stack space, while the iterative approach has a space complexity of O(1) since we are using constant space for storing the merged linked list.\n# C++\n- ### Code: Recursive Approach \n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n ListNode* ptr1 = list1;\n ListNode* ptr2 = list2;\n if(ptr1 == NULL){\n return list2;\n }\n if(ptr2 == NULL){\n return list1;\n }\n if(ptr1->val < ptr2->val){\n ptr1->next = mergeTwoLists(ptr1->next, ptr2);\n return ptr1;\n }\n else{\n ptr2->next = mergeTwoLists(ptr1, ptr2->next);\n return ptr2;\n }\n }\n};\n```\n- ### Code: Iterative Approach\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n ListNode* ans = new ListNode();\n ListNode* ptr = ans;\n while(list1 && list2){\n if(list1->val <= list2->val){\n ans->next = new ListNode(list1->val);\n list1 = list1->next;\n }\n else{\n ans->next = new ListNode(list2->val);\n list2 = list2->next;\n }\n ans = ans->next;\n }\n while(list1){\n ans->next = new ListNode(list1->val);\n list1 = list1->next;\n ans = ans->next;\n }\n while(list2){\n ans->next = new ListNode(list2->val);\n list2 = list2->next;\n ans = ans->next;\n }\n return ptr->next;\n }\n};\n```\n\n---\n\n# JavaScript\n- ### Code: Recursive Approach \n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nvar mergeTwoLists = function(l1, l2) {\n if (!l1) return l2;\n if (!l2) return l1;\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2;\n }\n};\n\n```\n- ### Code: Iterative Approach\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} list1\n * @param {ListNode} list2\n * @return {ListNode}\n */\nvar mergeTwoLists = function(list1, list2) {\n let ans = new ListNode();\n let ptr = ans;\n while(list1 && list2){\n if(list1.val <= list2.val){\n ans.next = new ListNode(list1.val);\n list1 = list1.next;\n }\n else{\n ans.next = new ListNode(list2.val);\n list2 = list2.next;\n }\n ans = ans.next;\n }\n while(list1){\n ans.next = new ListNode(list1.val);\n list1 = list1.next;\n ans = ans.next;\n }\n while(list2){\n ans.next = new ListNode(list2.val);\n list2 = list2.next;\n ans = ans.next;\n }\n return ptr.next;\n};\n\n```\n\n---\n\n# JAVA\n- ### Code: Recursive Approach \n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n if (list1 == null) return list2;\n if (list2 == null) return list1;\n if (list1.val < list2.val) {\n list1.next = mergeTwoLists(list1.next, list2);\n return list1;\n } else {\n list2.next = mergeTwoLists(list1, list2.next);\n return list2;\n }\n }\n}\n\n```\n- ### Code: Iterative Approach\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode ans = new ListNode();\n ListNode ptr = ans;\n while(list1 != null && list2 != null){\n if(list1.val <= list2.val){\n ans.next = new ListNode(list1.val);\n list1 = list1.next;\n }\n else{\n ans.next = new ListNode(list2.val);\n list2 = list2.next;\n }\n ans = ans.next;\n }\n while(list1 != null){\n ans.next = new ListNode(list1.val);\n list1 = list1.next;\n ans = ans.next;\n }\n while(list2 != null){\n ans.next = new ListNode(list2.val);\n list2 = list2.next;\n ans = ans.next;\n }\n return ptr.next;\n }\n}\n\n```\n\n---\n\n# Python\n### Code: Recursive Approach \n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution(object):\n def mergeTwoLists(self, l1, l2):\n """\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n """\n if not l1: return l2\n if not l2: return l1\n if l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\n else:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2\n\n```\n- ### Code: Iterative Approach\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def mergeTwoLists(self, list1, list2):\n """\n :type list1: Optional[ListNode]\n :type list2: Optional[ListNode]\n :rtype: Optional[ListNode]\n """\n ans = ListNode()\n ptr = ans\n while list1 and list2:\n if list1.val <= list2.val:\n ans.next = ListNode(list1.val)\n list1 = list1.next\n else:\n ans.next = ListNode(list2.val)\n list2 = list2.next\n ans = ans.next\n while list1:\n ans.next = ListNode(list1.val)\n list1 = list1.next\n ans = ans.next\n while list2:\n ans.next = ListNode(list2.val)\n list2 = list2.next\n ans = ans.next\n return ptr.next\n```\n
2,026
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
4,570
6
# Intuition\nThis question is asking you to merge 2 linked lists and return the head.\n\nThink of this question like you are inserting values between the head and the tail of a new empty list.\n\nWe start off by initalizing a head and movingtail to ListNode(). This makes head and tail both equal to an empty node. the head variable is commonly used and called the "dummy node". \n\nNext we loop through both lists and compare values to see which one is greater as we must merge both lists in increasing value. i named movingtail movingtail because it moves while head stays in place. Everytime one of the linked list nodes is greater than the other the tail moves/sets the next node equal to the "greater node" (movingtail.next = l1) and the "greater node" moves to the next node in that linked list. \n\nIf either linked list is empty this runs: (movingtail.next = l1 or l2) which sets movingtail equal to the linked list that isn\'t empty. \n\nAt the end of the program head.next returns, which means that the head or dummy node\'s next value (the head) will get returned which is the answer to the question.\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n head = movingtail = ListNode()\n \n while l1 and l2:\n if l1.val <= l2.val:\n movingtail.next = l1\n l1 = l1.next\n else:\n movingtail.next = l2\n l2 = l2.next\n movingtail = movingtail.next\n \n movingtail.next = l1 or l2\n return head.next\n```
2,032
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
71,076
475
**Solution 1**\n\nIf both lists are non-empty, I first make sure `a` starts smaller, use its head as result, and merge the remainders behind it. Otherwise, i.e., if one or both are empty, I just return what's there.\n\n class Solution:\n def mergeTwoLists(self, a, b):\n if a and b:\n if a.val > b.val:\n a, b = b, a\n a.next = self.mergeTwoLists(a.next, b)\n return a or b\n\n---\n\n**Solution 2**\n\nFirst make sure that `a` is the "better" one (meaning `b` is None or has larger/equal value). Then merge the remainders behind `a`.\n\n def mergeTwoLists(self, a, b):\n if not a or b and a.val > b.val:\n a, b = b, a\n if a:\n a.next = self.mergeTwoLists(a.next, b)\n return a
2,051
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
2,642
13
```python\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode(0) # making a dummy node\n curr = dummy # creating a pointer pointing to the dummy node\n \n while list1 and list2: # we must be having both list to perform merge operation.\n if list1.val < list2.val: # in case list value is less then list2,\n curr.next = list1 # then we move our pointer ahead in list 1.\n list1 = list1.next # having value of next element of list2\n else:\n curr.next = list2 # in case list2 value is greaer then list 1 value.\n list2 = list2.next #having value of next element of list2\n curr = curr.next # moving our curr pointer\n \n # In case all the elements of any one of the list is travered. then we`ll move our pointer to the left over. \n # As lists are soted already, technically we could do that\n # Method : 1\n# if list1:\n# curr.next = list1\n# elif list2:\n# curr.next = list2\n \n # Method : 2\n curr.next = list1 or list2\n \n return dummy.next # return next bcz first node is dummy. \n```\n***Found helpful, Do upvote !!***
2,068
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
1,416
11
**Explanation**\nHere we initialise two Linked List, one cur and another result with 0.\nWe use cur to connect all the nodes of two list in sorted way. The result is only use to remember the head of cur List.\nCur list not just take one node, instead it simply merges the whole list l1 or l2 and then increase the pointer.\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n # iteratively\n result = cur = ListNode(0)\n l1=list1\n l2=list2\n while l1 and l2:\n if l1.val < l2.val:\n cur.next = l1\n l1 = l1.next\n else:\n cur.next = l2\n l2 = l2.next\n cur = cur.next\n cur.next = l1 or l2\n return result.next\n\n```\n![image]()\n![image]()\n![image]()\n![image]()\n\n
2,075
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
97,050
1,292
1. The idea is to add `\')\'` only after valid `\'(\'`\n2. We use two integer variables `left` & `right` to see how many `\'(\'` & `\')\'` are in the current string\n3. If `left < n` then we can add `\'(\'` to the current string\n4. If `right < left` then we can add `\')\'` to the current string\n\n**Python Code:**\n```\ndef generateParenthesis(self, n: int) -> List[str]:\n\tdef dfs(left, right, s):\n\t\tif len(s) == n * 2:\n\t\t\tres.append(s)\n\t\t\treturn \n\n\t\tif left < n:\n\t\t\tdfs(left + 1, right, s + \'(\')\n\n\t\tif right < left:\n\t\t\tdfs(left, right + 1, s + \')\')\n\n\tres = []\n\tdfs(0, 0, \'\')\n\treturn res\n```\n\nFor` n = 2`, the recursion tree will be something like this,\n```\n\t\t\t\t\t\t\t\t \t(0, 0, \'\')\n\t\t\t\t\t\t\t\t \t |\t\n\t\t\t\t\t\t\t\t\t(1, 0, \'(\') \n\t\t\t\t\t\t\t\t / \\\n\t\t\t\t\t\t\t(2, 0, \'((\') (1, 1, \'()\')\n\t\t\t\t\t\t\t / \\\n\t\t\t\t\t\t(2, 1, \'(()\') (2, 1, \'()(\')\n\t\t\t\t\t\t / \\\n\t\t\t\t\t(2, 2, \'(())\') (2, 2, \'()()\')\n\t\t\t\t\t\t |\t |\n\t\t\t\t\tres.append(\'(())\') res.append(\'()()\')\n \n```\n\n**Java Code:**\n```java\nclass Solution {\n public List<String> generateParenthesis(int n) {\n List<String> res = new ArrayList<String>();\n recurse(res, 0, 0, "", n);\n return res;\n }\n \n public void recurse(List<String> res, int left, int right, String s, int n) {\n if (s.length() == n * 2) {\n res.add(s);\n return;\n }\n \n if (left < n) {\n recurse(res, left + 1, right, s + "(", n);\n }\n \n if (right < left) {\n recurse(res, left, right + 1, s + ")", n);\n }\n }\n\t// See above tree diagram with parameters (left, right, s) for better understanding\n}\n```\n![image]()\n\n\n![image]()\n\n\n\n
2,100
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
6,899
20
# Intuition:\nThe problem requires generating all possible combinations of well-formed parentheses of length 2n. To solve this, we can use a recursive approach. At each step, we have two choices: either add an opening parenthesis "(" or add a closing parenthesis ")". However, we need to make sure that the number of opening parentheses is always greater than or equal to the number of closing parentheses, so that the parentheses remain well-formed.\n\n# Approach:\n1. We define a helper function, `generateParentheses`, that takes the following parameters:\n - `result`: a reference to the vector of strings where we store the generated combinations.\n - `current`: the current combination being generated.\n - `open`: the count of opening parentheses "(" included in the current combination.\n - `close`: the count of closing parentheses ")" included in the current combination.\n - `n`: the total number of pairs of parentheses to be included.\n\n2. In the `generateParentheses` function, we first check if the length of the `current` string is equal to 2n. If it is, we have generated a valid combination, so we add it to the `result` vector and return.\n\n3. If the length of `current` is not equal to 2n, we have two choices:\n - If the count of opening parentheses `open` is less than n, we can add an opening parenthesis to the current combination and make a recursive call to `generateParentheses`, incrementing the `open` count by 1.\n - If the count of closing parentheses `close` is less than the `open` count, we can add a closing parenthesis to the current combination and make a recursive call to `generateParentheses`, incrementing the `close` count by 1.\n\n4. In the `generateParenthesis` function, we initialize an empty `result` vector and call the `generateParentheses` function with the initial values of `current` as an empty string, `open` and `close` counts as 0, and `n` as the input value.\n\n5. Finally, we return the `result` vector containing all the generated combinations of well-formed parentheses.\n\n# Complexity:\nThe time complexity of this solution is O(4^n / sqrt(n)), where n is the input number of pairs of parentheses.\nThe space complexity of this solution is O(n). \n\n---\n# C++\n```\nclass Solution {\npublic:\n void generateParentheses(vector<string>& result, string current, int open, int close, int n) {\n if (current.size() == 2 * n) {\n result.push_back(current);\n return;\n }\n if (open < n) {\n generateParentheses(result, current + \'(\', open + 1, close, n);\n }\n if (close < open) {\n generateParentheses(result, current + \')\', open, close + 1, n);\n }\n }\n vector<string> generateParenthesis(int n) {\n vector<string> result;\n generateParentheses(result, "", 0, 0, n);\n return result;\n }\n};\n```\n---\n# JAVA\n```\nclass Solution {\n public List<String> generateParenthesis(int n) {\n List<String> result = new ArrayList<>();\n generateParentheses(result, "", 0, 0, n);\n return result;\n }\n\n private void generateParentheses(List<String> result, String current, int open, int close, int n) {\n if (current.length() == 2 * n) {\n result.add(current);\n return;\n }\n if (open < n) {\n generateParentheses(result, current + \'(\', open + 1, close, n);\n }\n if (close < open) {\n generateParentheses(result, current + \')\', open, close + 1, n);\n }\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def generateParenthesis(self, n):\n result = []\n self.generateParentheses(result, "", 0, 0, n)\n return result\n\n def generateParentheses(self, result, current, open, close, n):\n if len(current) == 2 * n:\n result.append(current)\n return\n if open < n:\n self.generateParentheses(result, current + \'(\', open + 1, close, n)\n if close < open:\n self.generateParentheses(result, current + \')\', open, close + 1, n)\n\n```\n\n---\n# JavaScript\n```\nvar generateParenthesis = function(n) {\n const result = [];\n generateParentheses(result, \'\', 0, 0, n);\n return result;\n};\n\nconst generateParentheses = (result, current, open, close, n) => {\n if (current.length === 2 * n) {\n result.push(current);\n return;\n }\n if (open < n) {\n generateParentheses(result, current + \'(\', open + 1, close, n);\n }\n if (close < open) {\n generateParentheses(result, current + \')\', open, close + 1, n);\n }\n};\n```
2,130
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
96,959
429
`p` is the parenthesis-string built so far, `left` and `right` tell the number of left and right parentheses still to add, and `parens` collects the parentheses.\n\n**Solution 1**\n\nI used a few "tricks"... how many can you find? :-)\n\n def generateParenthesis(self, n):\n def generate(p, left, right, parens=[]):\n if left: generate(p + '(', left-1, right)\n if right > left: generate(p + ')', left, right-1)\n if not right: parens += p,\n return parens\n return generate('', n, n)\n\n**Solution 2**\n\nHere I wrote an actual Python generator. I allow myself to put the `yield q` at the end of the line because it's not that bad and because in "real life" I use Python 3 where I just say `yield from generate(...)`.\n\n def generateParenthesis(self, n):\n def generate(p, left, right):\n if right >= left >= 0:\n if not right:\n yield p\n for q in generate(p + '(', left-1, right): yield q\n for q in generate(p + ')', left, right-1): yield q\n return list(generate('', n, n))\n\n**Solution 3**\n\nImproved version of [this](). Parameter `open` tells the number of "already opened" parentheses, and I continue the recursion as long as I still have to open parentheses (`n > 0`) and I haven't made a mistake yet (`open >= 0`).\n\n def generateParenthesis(self, n, open=0):\n if n > 0 <= open:\n return ['(' + p for p in self.generateParenthesis(n-1, open+1)] + \\\n [')' + p for p in self.generateParenthesis(n, open-1)]\n return [')' * open] * (not n)
2,149
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
6,115
61
One thing we need to understand is, we need a way to add \u201C(\u201D and \u201C)\u201D to all possible cases and \nthen find a way to validate so that we don\u2019t generate the unnecessary ones.\n\nThe first condition is if there are more than 0 open / left brackets, we recurse with the right\nones. And if we have more than 0 right brackets, we recurse with the left ones. Left and right\nare initialized with` \'n\' `- the number given.\n\n\n```\n\t\t\tif left>0:\n helper(ans, s+\'(\', left-1, right)\n \n if right>0:\n helper(ans, s+\')\', left, right-1)\n```\n\n<br>\n\nThere\u2019s a catch. We can\u2019t add the \u201C)\u201D everytime we have `right>0` cause then it will not be\nbalanced. We can balance that with a simple condition of `left<right.`\n\n```\n\t\t\tif left>0:\n helper(ans, s+\'(\', left-1, right)\n \n if right>0 and left<right:\n helper(ans, s+\')\', left, right-1)\n```\n\n<br>\nSince this is a recursive approach we need to have a **BASE condition**,\nand the base case is: \n\nWhen both right and left are 0, \nwe have found one possible combination of parentheses \n& we now need to append/add the `\'s\'` to `\'ans\'` list.\n\n```\n\t\t\tif left==0 and right==0:\n ans.append(s)\n```\n\n<br>\n<br>\n\n**Complete code**\n```\nclass Solution:\n def generateParenthesis(self, n: int) -> List[str]:\n \n \n def helper(ans, s, left, right):\n if left==0 and right==0:\n ans.append(s)\n \n if left>0:\n helper(ans, s+\'(\', left-1, right)\n \n if right>0 and left<right:\n helper(ans, s+\')\', left, right-1)\n \n ans = []\n helper(ans, \'\', n, n)\n \n return ans\n```\n\n\n\n<br>\n<br>\n*If this post seems to be helpful, please upvote!!*
2,183
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
39,790
221
If you have two stacks, one for n "(", the other for n ")", you generate a binary tree from these two stacks of left/right parentheses to form an output string. \n\n\nThis means that whenever you traverse deeper, you pop one parentheses from one of stacks. When two stacks are empty, you form an output string.\n\nHow to form a legal string? Here is the simple observation:\n\n - For the output string to be right, stack of ")" most be larger than stack of "(". If not, it creates string like "())"\n - Since elements in each of stack are the same, we can simply express them with a number. For example, left = 3 is like a stacks ["(", "(", "("]\n\nSo, here is my sample code in Python:\n\n class Solution:\n # @param {integer} n\n # @return {string[]}\n def generateParenthesis(self, n):\n if not n:\n return []\n left, right, ans = n, n, []\n self.dfs(left,right, ans, "")\n return ans\n\n def dfs(self, left, right, ans, string):\n if right < left:\n return\n if not left and not right:\n ans.append(string)\n return\n if left:\n self.dfs(left-1, right, ans, string + "(")\n if right:\n self.dfs(left, right-1, ans, string + ")")
2,191
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
42,254
161
# Code\n\nPlease **Upvote** And **Comment** ....!\uD83D\uDE4F\uD83D\uDE4F\uD83D\uDE4F\n\n```JAVA []\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n return mergeKListsHelper(lists, 0, lists.length - 1);\n }\n \n private ListNode mergeKListsHelper(ListNode[] lists, int start, int end) {\n if (start == end) {\n return lists[start];\n }\n if (start + 1 == end) {\n return merge(lists[start], lists[end]);\n }\n int mid = start + (end - start) / 2;\n ListNode left = mergeKListsHelper(lists, start, mid);\n ListNode right = mergeKListsHelper(lists, mid + 1, end);\n return merge(left, right);\n }\n \n private ListNode merge(ListNode l1, ListNode l2) {\n ListNode dummy = new ListNode(0);\n ListNode curr = dummy;\n \n while (l1 != null && l2 != null) {\n if (l1.val < l2.val) {\n curr.next = l1;\n l1 = l1.next;\n } else {\n curr.next = l2;\n l2 = l2.next;\n }\n curr = curr.next;\n }\n \n curr.next = (l1 != null) ? l1 : l2;\n \n return dummy.next;\n }\n}\n\n\n```\n```python []\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n if not lists:\n return None\n if len(lists) == 1:\n return lists[0]\n \n mid = len(lists) // 2\n left = self.mergeKLists(lists[:mid])\n right = self.mergeKLists(lists[mid:])\n \n return self.merge(left, right)\n \n def merge(self, l1, l2):\n dummy = ListNode(0)\n curr = dummy\n \n while l1 and l2:\n if l1.val < l2.val:\n curr.next = l1\n l1 = l1.next\n else:\n curr.next = l2\n l2 = l2.next\n curr = curr.next\n \n curr.next = l1 or l2\n \n return dummy.next\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n if (lists.empty()) {\n return nullptr;\n }\n return mergeKListsHelper(lists, 0, lists.size() - 1);\n }\n \n ListNode* mergeKListsHelper(vector<ListNode*>& lists, int start, int end) {\n if (start == end) {\n return lists[start];\n }\n if (start + 1 == end) {\n return merge(lists[start], lists[end]);\n }\n int mid = start + (end - start) / 2;\n ListNode* left = mergeKListsHelper(lists, start, mid);\n ListNode* right = mergeKListsHelper(lists, mid + 1, end);\n return merge(left, right);\n }\n \n ListNode* merge(ListNode* l1, ListNode* l2) {\n ListNode* dummy = new ListNode(0);\n ListNode* curr = dummy;\n \n while (l1 && l2) {\n if (l1->val < l2->val) {\n curr->next = l1;\n l1 = l1->next;\n } else {\n curr->next = l2;\n l2 = l2->next;\n }\n curr = curr->next;\n }\n \n curr->next = l1 ? l1 : l2;\n \n return dummy->next;\n }\n};\n\n```\n![8873f9b1-dfa4-4d9c-bb67-1b6db9d65e35_1674992431.3815322.jpeg]()\n\n
2,202
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
788
5
\n[see the Successfully Accepted Submission]()\n```Python\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution(object):\n def mergeKLists(self, lists):\n # Create a new ListNode representing the head of the merged list.\n # Initialize it with an empty ListNode.\n newList = ListNode()\n # Create a temporary ListNode to build the merged list.\n temporary_list = newList\n\n # Define a helper function to get the smallest value among the current heads of all lists.\n def getSmallestValue():\n min_value = float(\'inf\') # Initialize the minimum value as positive infinity.\n min_index = -1 # Initialize the index of the list with the minimum value as -1.\n for i in range(len(lists)):\n # Check if the current list is not empty and its head value is smaller than the current minimum value.\n if lists[i] is not None and lists[i].val < min_value:\n min_value = lists[i].val\n min_index = i\n if min_index != -1:\n # If a list with the minimum value is found, move its head to the next element.\n lists[min_index] = lists[min_index].next\n return min_value\n \n # Loop to merge the lists.\n while True:\n x = getSmallestValue() # Get the smallest value among the current heads of lists.\n if x == float(\'inf\'):\n # If the smallest value is still positive infinity, all lists are empty, so break the loop.\n break\n # Create a new ListNode with the value of the smallest element.\n c = ListNode(val=x)\n # Connect the new node to the merged list.\n temporary_list.next = c\n temporary_list = temporary_list.next # Move the temporary list pointer forward.\n \n # Return the merged list, excluding the initial empty ListNode.\n return newList.next\n\n```\n\n![image]()\n\n\nPython | Easy | Heap | \n\n\n
2,210
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
8,361
65
**NOTE 1 - PLEASE READ INTUITION AND APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n**NOTE 2 - BEFORE SOLVING THIS PROBELM, I WILL HIGHLY RECOMMEND YOU TO SOLVE BELOW PROBLEM FOR BETTER UNDERSTANDING.**\n**21. Merge Two Sorted Lists :** \n**SOLUTION :** \n\n# Intuition of this Problem:\n**This solution uses the merge sort algorithm to merge all the linked lists in the input vector into a single sorted linked list. The merge sort algorithm works by recursively dividing the input into halves, sorting each half separately, and then merging the two sorted halves into a single sorted output.**\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach for this Problem:\n1. Define a function merge that takes two pointers to linked lists as input and merges them in a sorted manner.\n - a. Create a dummy node with a value of -1 and a temporary node pointing to it.\n - b. Compare the first node of the left and right linked lists, and append the smaller one to the temporary node.\n - c. Continue this process until either of the lists becomes empty.\n - d. Append the remaining nodes of the non-empty list to the temporary node.\n - e. Return the next node of the dummy node.\n\n1. Define a function mergeSort that takes three arguments - a vector of linked lists, a starting index, and an ending index. It performs merge sort on the linked lists from the starting index to the ending index.\n - a. If the starting index is equal to the ending index, return the linked list at that index.\n - b. Calculate the mid index and call mergeSort recursively on the left and right halves of the vector.\n - c. Merge the two sorted linked lists obtained from the recursive calls using the merge function and return the result.\n\n1. Define the main function mergeKLists that takes the vector of linked lists as input and returns a single sorted linked list.\n - a. If the input vector is empty, return a null pointer.\n - b. Call the mergeSort function on the entire input vector, from index 0 to index k-1, where k is the size of the input vector.\n - c. Return the merged linked list obtained from the mergeSort function call.\n1. End of algorithm.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n\n![57jfh9.jpg]()\n\n# Code:\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* merge(ListNode *left, ListNode *right) {\n ListNode *dummy = new ListNode(-1);\n ListNode *temp = dummy;\n while (left != nullptr && right != nullptr) {\n if (left -> val < right -> val) {\n temp -> next = left;\n temp = temp -> next;\n left = left -> next;\n }\n else {\n temp -> next = right;\n temp = temp -> next;\n right = right -> next;\n }\n }\n while (left != nullptr) {\n temp -> next = left;\n temp = temp -> next;\n left = left -> next;\n }\n while (right != nullptr) {\n temp -> next = right;\n temp = temp -> next;\n right = right -> next;\n }\n return dummy -> next;\n }\n ListNode* mergeSort(vector<ListNode*>& lists, int start, int end) {\n if (start == end) \n return lists[start];\n int mid = start + (end - start) / 2;\n ListNode *left = mergeSort(lists, start, mid);\n ListNode *right = mergeSort(lists, mid + 1, end);\n return merge(left, right);\n }\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n if (lists.size() == 0)\n return nullptr;\n return mergeSort(lists, 0, lists.size() - 1);\n }\n};\n```\n```Java []\nclass Solution {\n public ListNode merge(ListNode left, ListNode right) {\n ListNode dummy = new ListNode(-1);\n ListNode temp = dummy;\n while (left != null && right != null) {\n if (left.val < right.val) {\n temp.next = left;\n temp = temp.next;\n left = left.next;\n } else {\n temp.next = right;\n temp = temp.next;\n right = right.next;\n }\n }\n while (left != null) {\n temp.next = left;\n temp = temp.next;\n left = left.next;\n }\n while (right != null) {\n temp.next = right;\n temp = temp.next;\n right = right.next;\n }\n return dummy.next;\n }\n \n public ListNode mergeSort(List<ListNode> lists, int start, int end) {\n if (start == end) {\n return lists.get(start);\n }\n int mid = start + (end - start) / 2;\n ListNode left = mergeSort(lists, start, mid);\n ListNode right = mergeSort(lists, mid + 1, end);\n return merge(left, right);\n }\n \n public ListNode mergeKLists(List<ListNode> lists) {\n if (lists.size() == 0) {\n return null;\n }\n return mergeSort(lists, 0, lists.size() - 1);\n }\n}\n\n```\n```Python []\nclass Solution:\n def merge(self, left: ListNode, right: ListNode) -> ListNode:\n dummy = ListNode(-1)\n temp = dummy\n while left and right:\n if left.val < right.val:\n temp.next = left\n temp = temp.next\n left = left.next\n else:\n temp.next = right\n temp = temp.next\n right = right.next\n while left:\n temp.next = left\n temp = temp.next\n left = left.next\n while right:\n temp.next = right\n temp = temp.next\n right = right.next\n return dummy.next\n \n def mergeSort(self, lists: List[ListNode], start: int, end: int) -> ListNode:\n if start == end:\n return lists[start]\n mid = start + (end - start) // 2\n left = self.mergeSort(lists, start, mid)\n right = self.mergeSort(lists, mid + 1, end)\n return self.merge(left, right)\n \n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n if not lists:\n return None\n return self.mergeSort(lists, 0, len(lists) - 1)\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(N log k)**, where N is the total number of nodes in all the linked lists, and k is the number of linked lists in the input vector. This is because the merge sort algorithm requires O(N log N) time to sort N items, and in this case, N is the total number of nodes in all the linked lists. The number of levels in the recursion tree of the merge sort algorithm is log k, where k is the number of linked lists in the input vector. Each level of the recursion tree requires O(N) time to merge the sorted lists, so the total time complexity is O(N log k).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(log k)**, which is the maximum depth of the recursion tree of the merge sort algorithm. The space used by each recursive call is constant, so the total space used by the algorithm is proportional to the maximum depth of the recursion tree. Since the depth of the tree is log k, the space complexity of the algorithm is O(log k).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
2,211
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
1,394
7
# Intuition\nSince the constraints were:\n* length of lists, $$k = 10^4$$\n* length of each linked lists say $$n = 500$$\n \nIt was not a difficult choice to go for time complexity of $$O(kn)$$ \n\nAs we will get a TLE in python (generally) if we try to exceed $$O(10^8)$$.\nBut our solution takes $$O(10^4 * 500) < O(10^8)$$\n\n\n\n# Approach\n1. We will iterate through the lists and use the first element of each linked list to find the minimum among them, which will take $$O(k)$$ as length of list is $$k$$.\n2. We will follow step 1 till all the linked lists are completely explored. We will be able to do it in $$O(n)$$ time as length of any listed list is upper bounded by $$n$$.\n\n# Complexity\n- Time complexity: $$O(kn)$$ as both step 1 and step 2 are performed simultaneously.\n\n- Space complexity: $$O(n)$$ to create a new linked list whose length is upper bounded by n.\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n \n l = ListNode() # the new list that we want to return\n t = l # taking a temporary copy of the new list as we need to move to next pointers to store data.\n\n # get the minimum front value of all linked lists in the input list.\n def get_min():\n min_val, min_indx = float(\'inf\'), -1\n for i in range(len(lists)):\n if lists[i] != None and lists[i].val < min_val:\n min_val = lists[i].val\n min_indx = i\n if min_indx != -1:\n # when a min value is found, \n # increment the linked list \n # so that we don\'t consider the same min value the next time \n # and also the next value of linked list comes at the front\n lists[min_indx] = lists[min_indx].next\n return min_val\n \n while(1):\n x = get_min() # get the mim value to add to new list\n if (x == float(\'inf\')): \n # if min value is not obtained that means all the linked lists are traversed so break\n break\n c = ListNode(val=x)\n t.next = c\n t = t.next\n return l.next # as we made l to be just a head for our actual linked list\n \n\n\n\n\n \n\n\n```
2,232
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
7,593
33
# Please UPVOTE\uD83D\uDE0A\n![image.png]()\n\n\n# Python3\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n v=[]\n for i in lists:\n x=i\n while x:\n v+=[x.val]\n x=x.next\n v=sorted(v,reverse=True)\n ans=None\n for i in v:\n ans=ListNode(i,ans)\n return ans\n```\n# C++\n```\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n vector<int>v;\n for(int i=0;i<lists.size();i++){\n while(lists[i]){\n v.push_back(lists[i]->val);\n lists[i]=lists[i]->next;\n }\n }\n sort(rbegin(v),rend(v));\n ListNode* ans=nullptr;\n for(int i=0;i<v.size();i++){\n ans=new ListNode(v[i],ans);\n }\n return ans;\n }\n};\n```
2,234
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
3,045
31
# Intuition:\nThe problem can be solved by merging two sorted linked lists at a time. If we have K linked lists, we can merge the first and second linked lists, then merge the result with the third linked list, and so on. This process will result in a single sorted linked list containing all elements.\n\n# Approach:\n\n1. Define a function mergeTwoLists that takes two sorted linked lists as input and merges them into a single sorted linked list using a recursive approach.\n2. In the mergeKLists function, initialize a pointer ans to NULL.\n3. Iterate over the input vector lists, and at each iteration, merge ans with the current linked list using the mergeTwoLists function.\n4. Return ans.\n# Complexity:\n\n- Time complexity: \nThe time complexity of this solution is O(N log k), where N is the total number of elements in all linked lists, and k is the number of linked lists. The reason for this complexity is that we are merging two lists at a time, and the number of merged lists is reduced by a factor of 2 at each iteration. Thus, the total number of iterations is log k. In each iteration, we perform N comparisons and updates, so the total time complexity is O(N log k).\n\n- Space Complexity:\nThe space complexity of this solution is O(1) since we are not using any additional data structures. The only extra space used is the recursion stack space, which is O(log k) for the recursive approach used in mergeTwoLists.\n\n---\n# C++\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n // Recursive Approach \n ListNode* ptr1 = list1;\n ListNode* ptr2 = list2;\n if(ptr1 == NULL){\n return list2;\n }\n if(ptr2 == NULL){\n return list1;\n }\n if(ptr1->val < ptr2->val){\n ptr1->next = mergeTwoLists(ptr1->next, ptr2);\n return ptr1;\n }\n else{\n ptr2->next = mergeTwoLists(ptr1, ptr2->next);\n return ptr2;\n }\n }\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n ListNode* ans = NULL;\n int count=0;\n while(count<lists.size()){\n ans = mergeTwoLists(ans,lists[count]);\n count++;\n }\n return ans;\n }\n};\n```\n\n---\n# Java\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n if (l1 == null) {\n return l2;\n }\n if (l2 == null) {\n return l1;\n }\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2;\n }\n }\n\n public ListNode mergeKLists(ListNode[] lists) {\n ListNode ans = null;\n for (int i = 0; i < lists.length; i++) {\n ans = mergeTwoLists(ans, lists[i]);\n }\n return ans;\n }\n}\n\n```\n---\n# JavaScript\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode[]} lists\n * @return {ListNode}\n */\nvar mergeTwoLists = function(l1, l2) {\n if (!l1) {\n return l2;\n }\n if (!l2) {\n return l1;\n }\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2;\n }\n};\n\nvar mergeKLists = function(lists) {\n let ans = null;\n for (let i = 0; i < lists.length; i++) {\n ans = mergeTwoLists(ans, lists[i]);\n }\n return ans;\n};\n\n```\n---\n# Python\n### Different Approach\n- To avoid the "Time Limit Exceeded" error, we can use a more efficient approach using a min-heap or priority queue.\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution(object):\n def mergeKLists(self, lists):\n # Create a min-heap and initialize it with the first node of each list\n heap = []\n for i in range(len(lists)):\n if lists[i]:\n heapq.heappush(heap, (lists[i].val, i))\n\n # Create a dummy node to build the merged list\n dummy = ListNode(0)\n current = dummy\n\n # Merge the lists using the min-heap\n while heap:\n val, index = heapq.heappop(heap)\n current.next = lists[index]\n current = current.next\n lists[index] = lists[index].next\n if lists[index]:\n heapq.heappush(heap, (lists[index].val, index))\n\n return dummy.next\n\n```\n> # ***Thanks For Voting***
2,243
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
24,000
168
**Python 2 Solution:**\n```\ndef mergeKLists_Python2(self, lists):\n\th = []\n\thead = tail = ListNode(0)\n\tfor i in lists:\n\t\tif i:\n\t\t\theapq.heappush(h, (i.val, i))\n\n\twhile h:\n\t\tnode = heapq.heappop(h)[1]\n\t\ttail.next = node\n\t\ttail = tail.next\n\t\tif node.next:\n\t\t\theapq.heappush(h, (node.next.val, node.next))\n\n\treturn head.next\n```\n\n**Python 3:** \nThe above solution works fine with Python 2.However, with Python3 it gives Type Error:\nTypeError: \'<\' not supported between instances of \'ListNode\' and \'ListNode\'\n**This error occurs because the cmp() special method is no longer honored in Python 3**\n\nHere are the two ways we can solve this problem:\n**a) Implement eq, lt methods** \n\t\nOne of the solution would be to provide `__eq__ and __lt__` method implementation to `ListNode` class\n```\ndef mergeKLists_Python3(self, lists):\n\tListNode.__eq__ = lambda self, other: self.val == other.val\n\tListNode.__lt__ = lambda self, other: self.val < other.val\n\th = []\n\thead = tail = ListNode(0)\n\tfor i in lists:\n\t\tif i:\n\t\t\theapq.heappush(h, (i.val, i))\n\n\twhile h:\n\t\tnode = heapq.heappop(h)[1]\n\t\ttail.next = node\n\t\ttail = tail.next\n\t\tif node.next:\n\t\t\theapq.heappush(h, (node.next.val, node.next))\n\n\treturn head.next\n```\n\n**b) Fix heapq** \n\nThe problem while adding `ListNode` objects as tasks is that the Tuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order. The solution is to store entries as 3-element list including the priority, an entry count, and the task.\nThe entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added.\nAnd since no two entry counts are the same, the tuple comparison will never attempt to directly compare two tasks.\n\n```\ndef mergeKLists_heapq(self, lists):\n\th = []\n\thead = tail = ListNode(0)\n\tfor i in range(len(lists)):\n\t\theapq.heappush(h, (lists[i].val, i, lists[i]))\n\n\twhile h:\n\t\tnode = heapq.heappop(h)\n\t\tnode = node[2]\n\t\ttail.next = node\n\t\ttail = tail.next\n\t\tif node.next:\n\t\t\ti+=1\n\t\t\theapq.heappush(h, (node.next.val, i, node.next))\n\n\treturn head.next\n```\n\t
2,250