title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
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
2,703
6
![image.png]()\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEach digit in the keypad is mapped with a set of characters that forms a string. Once a digt is pressed, we are faced with the choice of deciding which character to choose from the string it represents. This process continues for each subsequent digit that it pressed.\n\nUltimately, we are simply deciding which character to choose from the string represented by the digit and we keep on repeating this process, generating subcases for each choice, till we exhaust the string of digits given to us.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitialize a vector of strings `charMap` that stores the string of characters mapped to each digit of its index. Now, call the function `generateCombos` and pass to it `charMap` along with the starting index of `digits`, the string `digits`, a temporary string `temp` to store the strings generated and the vector of strings `sol` to store the possible combinations of strings generated.\n\nInitialize an integer `num` and assign to it the numerical value represented by the `idx`th index of digits. Now, initialize a string `str`, and assign to it the string represented by the digit.\n\nIterate `str` and push into temp each of its characters. Afterwards, recursively call `generateCombos` with the next index of digits. Once the function call has been returned, pop out the character that was pushed into `temp` and move on the next character of `str`.\n\nOnce `idx` becomes equal to the length of `digits`, push into `sol` the non-empty string `temp`.\n\n# Complexity\n- Time complexity: $$O(N)$$, where \'N\' is the length of the digits array\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$, since the only extra space we are using is for `charMap` and it always occupies 28 bytes.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void generateCombos(int idx, string& digits, string& temp, vector<string>& sol, vector<string>& charMap){\n if(idx==digits.length()){\n if(temp.length()) sol.push_back(temp);\n return;\n }\n\n int num=digits[idx]-\'0\';\n string str=charMap[num];\n\n for(int i=0;i<str.length();i++){\n temp.push_back(str[i]);\n generateCombos(idx+1, digits, temp, sol, charMap);\n temp.pop_back();\n }\n }\n\n vector<string> letterCombinations(string digits) {\n string temp;\n vector<string> sol;\n vector<string> charMap={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n\n generateCombos(0, digits, temp, sol, charMap);\n return sol;\n }\n};\n```
1,623
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,455
138
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using Two Approaches.\n\n1. Solved using String + Backtracking + Hash Table. Recursive Approach.\n2. Solved using String + Hash Table. Iterative Approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the all the approaches by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity : O(3^N \xD7 4^M) where N is the number of digits which have 3 letters( ex: 2,3,4) assigned to it and M is the number of digits which has 4 letters(ex: 7,9) assigned to it.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity : O(3^N \xD7 4^M) where N is the number of digits which have 3 letters( ex: 2,3,4) assigned to it and M is the number of digits which has 4 letters(ex: 7,9) assigned to it.\n\n# Code\n```\n/*\n\n Time Complexity : O(3^N \xD7 4^M) where N is the number of digits which have 3 letters( ex: 2,3,4) assigned to\n it and M is the number of digits which has 4 letters(ex: 7,9) assigned to it.\n\n Space Complexity : O(3^N \xD7 4^M) where N is the number of digits which have 3 letters( ex: 2,3,4) assigned to\n it and M is the number of digits which has 4 letters(ex: 7,9) assigned to it.\n\n Solved using String + Backtracking + Hash Table. Recursive Approach.\n\n*/\n\n\n/***************************************** Approach 1 *****************************************/\n\nclass Solution {\nprivate:\n void letterCombinations(string digits, vector<string>& output, string &temp, vector<string>& pad, int index){\n if(index == digits.size()){\n output.push_back(temp);\n return;\n }\n string value = pad[digits[index]-\'0\'];\n for(int i=0; i<value.size(); i++){\n temp.push_back(value[i]);\n letterCombinations(digits, output, temp, pad, index+1);\n temp.pop_back();\n }\n }\npublic:\n vector<string> letterCombinations(string digits) {\n if(digits.empty()){\n return {};\n }\n vector<string> pad = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n vector<string> output;\n string temp;\n letterCombinations(digits, output, temp, pad, 0);\n return output;\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(3^N \xD7 4^M) where N is the number of digits which have 3 letters( ex: 2,3,4) assigned to\n it and M is the number of digits which has 4 letters(ex: 7,9) assigned to it.\n\n Space Complexity : O(3^N \xD7 4^M) where N is the number of digits which have 3 letters( ex: 2,3,4) assigned to\n it and M is the number of digits which has 4 letters(ex: 7,9) assigned to it.\n\n Solved using String + Hash Table. Iterative Approach.\n\n*/\n\n\n/***************************************** Approach 2 *****************************************/\n\nclass Solution {\npublic:\n vector<string> letterCombinations(string digits) {\n if(digits.empty()){\n return {};\n }\n vector<string> pad = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n vector<string> output;\n output.push_back("");\n for(auto key : digits){\n vector<string> temp;\n for(auto candidate : pad[key-\'0\']){\n for(auto c : output){\n temp.push_back(c + candidate);\n }\n }\n output.clear();\n output = temp;\n }\n return output;\n }\n};\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]()
1,629
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
231,442
1,224
```\npublic List<String> letterCombinations(String digits) {\n\t\tLinkedList<String> ans = new LinkedList<String>();\n\t\tif(digits.isEmpty()) return ans;\n\t\tString[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n\t\tans.add("");\n\t\tfor(int i =0; i<digits.length();i++){\n\t\t\tint x = Character.getNumericValue(digits.charAt(i));\n\t\t\twhile(ans.peek().length()==i){\n\t\t\t\tString t = ans.remove();\n\t\t\t\tfor(char s : mapping[x].toCharArray())\n\t\t\t\t\tans.add(t+s);\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n```\n\nA version without first loop, but same time complexity. Both are single queue BFS solutions.:\n```\npublic List<String> letterCombinations(String digits) {\n\t\tLinkedList<String> ans = new LinkedList<String>();\n\t\tif(digits.isEmpty()) return ans;\n\t\tString[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n\t\tans.add("");\n\t\twhile(ans.peek().length()!=digits.length()){\n\t\t\tString remove = ans.remove();\n\t\t\tString map = mapping[digits.charAt(remove.length())-\'0\'];\n\t\t\tfor(char c: map.toCharArray()){\n\t\t\t\tans.addLast(remove+c);\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n```
1,634
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
2,645
7
# Code\n```\nclass Solution {\npublic:\n map<char,string> data;\n\n void fillData(){\n data[\'2\'] = "abc";\n data[\'3\'] = "def";\n data[\'4\'] = "ghi";\n data[\'5\'] = "jkl";\n data[\'6\'] = "mno";\n data[\'7\'] = "pqrs";\n data[\'8\'] = "tuv";\n data[\'9\'] = "wxyz";\n }\n\n void helper(vector<string>&res, string temp, int i, string digits, int j){\n if(temp.length() == digits.length() && temp != "") {\n res.push_back(temp);\n return;\n }\n if(i >= digits.length()) return;\n\n for(int idx = j; idx < data[digits[i]].length(); idx++){\n temp.push_back(data[digits[i]][idx]);\n helper(res,temp,i+1,digits,j);\n temp.pop_back();\n }\n }\n\n vector<string> letterCombinations(string digits) {\n fillData();\n vector<string> res;\n string temp = "";\n\n helper(res,temp,0,digits,0);\n\n return res;\n }\n};\n```
1,643
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,206
5
# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Key observation: It\'s easy to use vector instead of map, better extraction and same time complexity as map.\n- Use backtracking for getting all possible permutations.\n- If the digits is empty, return empty vector of string.\n\n\n# Complexity\n- Time complexity: O(n*4^n): In worst case for digit having 4 character.have choice of 4. n digit we have to select.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n): At most the temp can store is upto n.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void Helper(int idx, int n, string &digits, vector<string> &dict, vector<string> &ans, string temp){\n\n if(idx==n){\n ans.push_back(temp);\n return;\n }\n string val = dict[digits[idx]-\'0\'];\n for(int i=0; i<val.size(); i++){\n temp+=val[i];\n Helper(idx+1,n,digits,dict,ans,temp);\n temp.pop_back(); // backtrack\n }\n }\n\n vector<string> letterCombinations(string digits) {\n vector<string> ans;\n int n = digits.size();\n vector<string> dict = {"", "", "abc", "def", "ghi","jkl", "mno","pqrs", "tuv", "wxyz"}; // as 0 means nothing and pressing 1 results nothing here.\n if(n==0)return ans; // base case\n Helper(0,n,digits,dict,ans,"");\n return ans;\n }\n};\n```
1,650
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
1,255
6
# Approach\nSimpe bruteforce backtracking \n\n\n# Code\n```\nclass Solution {\n List<String> res = null;\n String [] strMap = {"0","1","abc", "def","ghi","jkl","mno","pqrs","tuv","wxyz"};\n public List<String> letterCombinations(String digits) {\n res = new ArrayList<>();\n if(digits.length() == 0){\n return res;\n }\n dfs(0,digits,new StringBuilder());\n return res;\n }\n\n void dfs(int length ,String digits,StringBuilder temp){\n\n if(length == digits.length()){\n res.add(temp.toString());\n return; \n }\n\n char ch = digits.charAt(length);\n String str = strMap[ch -\'0\'];\n\n for(char c:str.toCharArray()){\n temp.append(c);\n dfs(length+1,digits,temp);\n temp.deleteCharAt(temp.length()-1);\n }\n\n }\n}\n```
1,652
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,468
9
This is a direct recursive implementation, where we append all the characters of this digit to the currently formed string, and call recursive function for the next digits. \n* If, the length is zero, we return directly.\n* Else, we form a vector representing the phone characters for this letter and call the recursive function. Go through the recursive function to understand completely.\n\n**Full Code:**\n```\nclass Solution {\npublic:\n vector<string> ans;\n void combinations(string digits, string currString, vector<string> numbers, int start, int end){\n if(start == end)ans.push_back(currString);\n else{\n int index = digits[start]-\'0\';\n for(int i=0; i<numbers[index].length(); i++)\n combinations(digits, currString+numbers[index][i], numbers, start+1, end);\n }\n }\n vector<string> letterCombinations(string digits) {\n if(digits.length()==0)return ans;\n vector<string> numbers = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n combinations(digits,"", numbers, 0, digits.length());\n return ans;\n }\n};\n```\n**In case you found the post useful, please give it an upvote.**
1,660
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,322
10
# Intuition\nThe problem is to find all possible letter combinations that a given number could represent, as mapped on a telephone\'s buttons. Big thanks to vanAmsen for interacive video agood for inspiration [17. Letter Combinations of a Phone Number]() The initial thought is to create a mapping between the digits and their corresponding letters and then use recursion to explore all possible combinations. \n\n# Approach\n1. **Initialize a Mapping**: Create an array mapping the digits 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. **Define Recursive Function**: Utilize a recursive function `backtrack` that takes the current combination and the next digits to explore.\n - **Termination Condition**: If there are no more digits to explore, append the current combination to the result.\n - **Exploration**: Iterate through the corresponding letters of the next digit and recursively explore the remaining digits.\n4. **Result**: Return the collected 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, 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\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```\n``` TypeScript []\nfunction letterCombinations(digits: string): string[] {\n if (digits.length === 0) return [];\n\n const phoneMap: string[] = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];\n const output: string[] = [];\n\n function backtrack(combination: string, nextDigits: string) {\n if (nextDigits.length === 0) {\n output.push(combination);\n } else {\n const letters: string = phoneMap[parseInt(nextDigits[0]) - 2];\n for (const letter of letters) {\n backtrack(combination + letter, nextDigits.slice(1));\n }\n }\n }\n\n backtrack("", digits);\n return output;\n}\n```\n``` Ruby []\n# @param {String} digits\n# @return {String[]}\ndef letter_combinations(digits)\n return [] if digits.empty?\n\n phone_map = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]\n output = []\n\n def backtrack(combination, next_digits, phone_map, output)\n if next_digits.empty?\n output << combination\n else\n letters = phone_map[next_digits[0].to_i - 2]\n letters.each_char do |letter|\n backtrack(combination + letter, next_digits[1..], phone_map, output)\n end\n end\n end\n\n backtrack("", digits, phone_map, output)\n output\nend\n```\n``` Swift []\nclass Solution {\n func letterCombinations(_ digits: String) -> [String] {\n if digits.isEmpty {\n return []\n }\n\n let phoneMap = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]\n var output: [String] = []\n\n func backtrack(_ combination: String, _ nextDigits: String) {\n if nextDigits.isEmpty {\n output.append(combination)\n } else {\n let letters = phoneMap[Int(String(nextDigits.first!))! - 2]\n for letter in letters {\n backtrack(combination + String(letter), String(nextDigits.dropFirst()))\n }\n }\n }\n\n backtrack("", digits)\n return output\n }\n}\n```\nThis code follows the recursive backtracking approach to find all possible letter combinations, similar to the previous implementations in other languages, and adapts it to Go\'s syntax and constructs.
1,661
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
89,866
653
```\n\nclass Solution {\npublic:\n const vector<string> pad = {\n "", "", "abc", "def", "ghi", "jkl",\n "mno", "pqrs", "tuv", "wxyz"\n };\n \n vector<string> letterCombinations(string digits) {\n if (digits.empty()) return {};\n\t\tvector<string> result;\n result.push_back("");\n \n for(auto digit: digits) {\n vector<string> tmp;\n for(auto candidate: pad[digit - \'0\']) {\n for(auto s: result) {\n tmp.push_back(s + candidate);\n }\n }\n result.swap(tmp);\n }\n return result;\n }\n};\n```\n\nSimple and efficient iterative solution.\n\nExplanation with sample input "123"\n\nInitial state:\n\n- result = {""}\n\nStage 1 for number "1":\n\n- result has {""}\n- candiate is "abc"\n- generate three strings "" + "a", ""+"b", ""+"c" and put into tmp,\n tmp = {"a", "b","c"}\n- swap result and tmp (swap does not take memory copy)\n- Now result has {"a", "b", "c"}\n \nStage 2 for number "2":\n\n- result has {"a", "b", "c"}\n- candidate is "def"\n- generate nine strings and put into tmp,\n "a" + "d", "a"+"e", "a"+"f", \n "b" + "d", "b"+"e", "b"+"f",\n "c" + "d", "c"+"e", "c"+"f" \n- so tmp has {"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" }\n- swap result and tmp\n- Now result has {"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" }\n\nStage 3 for number "3":\n\n- result has {"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" }\n- candidate is "ghi"\n- generate 27 strings and put into tmp,\n- add "g" for each of "ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" \n- add "h" for each of "ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" \n- add "h" for each of "ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" \n- so, tmp has\n {"adg", "aeg", "afg", "bdg", "beg", "bfg", "cdg", "ceg", "cfg"\n "adh", "aeh", "afh", "bdh", "beh", "bfh", "cdh", "ceh", "cfh" \n "adi", "aei", "afi", "bdi", "bei", "bfi", "cdi", "cei", "cfi" }\n- swap result and tmp\n- Now result has\n {"adg", "aeg", "afg", "bdg", "beg", "bfg", "cdg", "ceg", "cfg"\n "adh", "aeh", "afh", "bdh", "beh", "bfh", "cdh", "ceh", "cfh" \n "adi", "aei", "afi", "bdi", "bei", "bfi", "cdi", "cei", "cfi" }\n\n\nFinally, return result.
1,665
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
1,636
11
# Code\n```\nclass Solution {\npublic:\n void generateCombos(int idx, string& digits, string& temp, vector<string>& sol, vector<string>& charMap){\n if(idx==digits.length()){\n if(temp.length()) sol.push_back(temp);\n return;\n }\n int num=digits[idx]-\'0\';\n string str=charMap[num];\n\n for(int i=0;i<str.length();i++){\n temp.push_back(str[i]);\n generateCombos(idx+1, digits, temp, sol, charMap);\n temp.pop_back();\n }\n }\n vector<string> letterCombinations(string digits) {\n string temp;\n vector<string> sol;\n vector<string> charMap={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};\n generateCombos(0, digits, temp, sol, charMap);\n return sol;\n }\n};\n```\n![upvote (2).jpg]()\n
1,680
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
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
4,362
5
class Solution {\npublic: \n\n\n\n void solve(string digits , string output , int index , vector<string>& ans , string mapping[]){\n \n //base case\n if(index >= digits.length()){\n ans.push_back(output);\n return ;\n }\n \n int number = digits[index] - \'0\';\n string value = mapping[number];\n \n for(int i = 0 ; i<value.length() ; i++){\n output.push_back(value[i]);\n solve(digits , output , index+1 , ans , mapping);\n output.pop_back();\n }\n \n }\n\n vector<string> letterCombinations(string digits) {\n \n vector<string> ans;\n if(digits.length() == 0){\n return ans;\n }\n \n string output = "";\n int index = 0;\n string mapping[10] = {"" , "","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};\n \n solve(digits , output , index , ans , mapping);\n return ans;\n }\n \n \n};
1,686
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
37,416
300
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this question using Multiple Approaches. (Here I have explained all the possible solutions of this problem).\n\n1. Solved using Array(Four Nested Loop) + Sorting + Hash Table(set). Brute Force Approach.\n2. Solved using Array(Three Nested Loop) + Sorting + Hash Table(set).\n3. Solved using Array(Three Nested Loop) + Sorting. Optimized Approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the All the approaches by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is given in code comment.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity is given in code comment.\n\n# Code\n```\n/*\n\n Time Complexity : O(N^4), Here Four nested loop creates the time complexity. Where N is the size of the\n array(nums).\n\n Space Complexity : O(N), Hash Table(set) space.\n\n Solved using Array(Four Nested Loop) + Sorting + Hash Table(set). Brute Force Approach.\n\n Note : this will give TLE.\n\n*/\n\n\n/***************************************** Approach 1 *****************************************/\n\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n set<vector<int>> set;\n vector<vector<int>> output;\n for(int i=0; i<n-3; i++){\n for(int j=i+1; j<n-2; j++){\n for(int k=j+1; k<n-1; k++){\n for(int l=k+1; l<n; l++){\n if((long long)nums[i] + (long long)nums[j] + (long long)nums[k] + \n (long long)nums[l] == target){\n set.insert({nums[i], nums[j], nums[k], nums[l]});\n }\n }\n }\n }\n }\n for(auto it : set){\n output.push_back(it);\n }\n return output;\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(N^3), Here Three nested loop creates the time complexity. Where N is the size of the\n array(nums).\n\n Space Complexity : O(N), Hash Table(set) space.\n\n Solved using Array(Three Nested Loop) + Sorting + Hash Table(set).\n\n*/\n\n\n/***************************************** Approach 2 *****************************************/\n\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n set<vector<int>> set;\n vector<vector<int>> output;\n for(int i=0; i<n-3; i++){\n for(int j=i+1; j<n-2; j++){\n long long newTarget = (long long)target - (long long)nums[i] - (long long)nums[j];\n int low = j+1, high = n-1;\n while(low < high){\n if(nums[low] + nums[high] < newTarget){\n low++;\n }\n else if(nums[low] + nums[high] > newTarget){\n high--;\n }\n else{\n set.insert({nums[i], nums[j], nums[low], nums[high]});\n low++; high--;\n }\n }\n }\n }\n for(auto it : set){\n output.push_back(it);\n }\n return output;\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(N^3), Here Three nested loop creates the time complexity. Where N is the size of the\n array(nums).\n\n Space Complexity : O(1), Constant space. Extra space is only allocated for the Vector(output), however the\n output does not count towards the space complexity.\n\n Solved using Array(Three Nested Loop) + Sorting. Optimized Approach.\n\n*/\n\n\n/***************************************** Approach 3 *****************************************/\n\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n vector<vector<int>> output;\n for(int i=0; i<n-3; i++){\n for(int j=i+1; j<n-2; j++){\n long long newTarget = (long long)target - (long long)nums[i] - (long long)nums[j];\n int low = j+1, high = n-1;\n while(low < high){\n if(nums[low] + nums[high] < newTarget){\n low++;\n }\n else if(nums[low] + nums[high] > newTarget){\n high--;\n }\n else{\n output.push_back({nums[i], nums[j], nums[low], nums[high]});\n int tempIndex1 = low, tempIndex2 = high;\n while(low < high && nums[low] == nums[tempIndex1]) low++;\n while(low < high && nums[high] == nums[tempIndex2]) high--;\n }\n }\n while(j+1 < n && nums[j] == nums[j+1]) j++;\n }\n while(i+1 < n && nums[i] == nums[i+1]) i++;\n }\n return output;\n }\n};\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]()
1,702
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
19,453
277
**\u2714\uFE0F Solution 1: HashSet**\n- The idea is to use `HashSet` to track past elements.\n- We iterate the combinations of `nums[i]`, `nums[j]`, `nums[k]`, and calculate the last number by `lastNumber = target - nums[i] - nums[j] - nums[k]`. \n- We check if `lastNumber` is existed the past by checking in the HashSet, if existed, then it form a `quadruplets` then add it to the answer.\n\nCredit @archit91 for providing C++ version.\n<iframe src="" frameBorder="0" width="100%" height="450"></iframe>\n\nComplexity:\n- Time: `O(N^3)`\n- Extra Space (Without count output as space): `O(N)`\n---\n**\u2714\uFE0F Solution 2: Sort then Two Pointers**\n- Sort `nums` in increasing order.\n- We fix `nums[i], nums[j]` by iterating the combination of `nums[i], nums[j]`, then the problem now become to very classic problem **[1. Two Sum]()**.\n- By using two pointers, one points to `left`, the other points to `right`, `remain = target - nums[i] - nums[j]`.\n\t- If `nums[left] + nums[right] == remain`\n\t\t- Found a valid quadruplets\n\t- Else if `nums[left] + nums[right] > remain`\n\t\t- Sum is bigger than remain, need to decrease sum by `right -= 1`\n\t- Else:\n\t\t- Increasing sum by `left += 1`.\n\n<iframe src="" frameBorder="0" width="100%" height="550"></iframe>\n\nComplexity:\n- Time: `O(N^3)`\n- Extra Space (Without count output as space): `O(sorting)`\n\n---\n**\u2714\uFE0F Follow-up question: Calculate K-Sum?**\n\n<iframe src="" frameBorder="0" width="100%" height="600"></iframe>\n\nComplexity:\n- Time: `O(NlogN + N^(k-1))`, where `k >= 2`, `N` is number of elements in the array `nums`.\n- Extra space (Without count output as space): `O(N)`\n\nIf you think this **post is useful**, I\'m happy if you **give a vote**. Any **questions or discussions are welcome!** Thank a lot.
1,705
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
989
5
# Brute Force--->O(N^4)--->[TLE]\n```\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n ans=[]\n n=len(nums)\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 temp=nums[i]+nums[j]+nums[k]+nums[l]\n sorted_num=sorted([nums[i],nums[j],nums[k],nums[l]])\n if temp==target and sorted_num not in ans:\n ans.append(sorted_num)\n return ans\n```\n# Optimised Approach-->Two Pointers Appraoch ----> O(N^3)---->[Accepted]\n```\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n ans=[]\n n=len(nums)\n nums.sort()\n for i in range(n-3):\n for j in range(i+1,n-2):\n k=j+1\n l=n-1\n while k<l:\n temp=nums[i]+nums[j]+nums[k]+nums[l]\n sorted_num=sorted([nums[i],nums[j],nums[k],nums[l]])\n if temp==target and sorted_num not in ans:\n ans.append(sorted_num)\n elif temp>target:\n l-=1\n else:\n k+=1\n return ans\n ```\n # Using Hashset----->O(N^3)---->[Accepted]\n ```\n class Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n ans=set()\n n=len(nums)\n nums.sort()\n for i in range(n-3):\n for j in range(i+1,n-2):\n k=j+1\n l=n-1\n while k<l:\n temp=nums[i]+nums[j]+nums[k]+nums[l]\n if temp==target:\n ans.add((nums[i],nums[j],nums[k],nums[l]))\n k+=1\n elif temp>target:\n l-=1\n else:\n k+=1\n return list(ans)\n ```\n # please upvote me it would encourage me alot\n\n
1,712
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
579
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>>v;\n sort(nums.begin(),nums.end());\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n if(i>0&& nums[i]==nums[i-1])continue;\n for(int j=i+1;j<n;j++)\n {\n if(j!=(i+1) && nums[j]==nums[j-1])continue;\n int k=j+1;\n int l=n-1;\n while(k<l)\n {\n long long sum=nums[i];\n sum+=nums[j];\n sum+=nums[k];\n sum+=nums[l];\n if(sum==target)\n {\n vector<int> temp={nums[i],nums[j],nums[k],nums[l]};\n v.push_back(temp);\n k=k+1;\n l=l-1;\n while(k<l && nums[k]==nums[k-1])k=k+1;\n while(k<l && nums[l]==nums[l+1])l=l-1;\n }\n else if(sum<target)\n {\n k++;\n }\n else{l--;}\n }\n }\n } \n return v;\n }\n};\n```
1,713
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
77,195
475
#### General Idea\nIf you have already read and implement the 3sum and 4sum by using the sorting approach: reduce them into 2sum at the end, you might already got the feeling that, all ksum problem can be divided into two problems: \n1. 2sum Problem\n2. Reduce K sum problem to K \u2013 1 sum Problem\n\nTherefore, the ideas is simple and straightforward. We could use recursive to solve this problem. Time complexity is O(N^(K-1)).\n\n```JAVA\n public class Solution {\n int len = 0;\n public List<List<Integer>> fourSum(int[] nums, int target) {\n len = nums.length;\n Arrays.sort(nums);\n return kSum(nums, target, 4, 0);\n }\n private ArrayList<List<Integer>> kSum(int[] nums, int target, int k, int index) {\n ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();\n if(index >= len) {\n return res;\n }\n if(k == 2) {\n \tint i = index, j = len - 1;\n \twhile(i < j) {\n //find a pair\n \t if(target - nums[i] == nums[j]) {\n \t \tList<Integer> temp = new ArrayList<>();\n \ttemp.add(nums[i]);\n \ttemp.add(target-nums[i]);\n res.add(temp);\n //skip duplication\n while(i<j && nums[i]==nums[i+1]) i++;\n while(i<j && nums[j-1]==nums[j]) j--;\n i++;\n j--;\n //move left bound\n \t } else if (target - nums[i] > nums[j]) {\n \t i++;\n //move right bound\n \t } else {\n \t j--;\n \t }\n \t}\n } else{\n for (int i = index; i < len - k + 1; i++) {\n //use current number to reduce ksum into k-1sum\n ArrayList<List<Integer>> temp = kSum(nums, target - nums[i], k-1, i+1);\n if(temp != null){\n //add previous results\n for (List<Integer> t : temp) {\n t.add(0, nums[i]);\n }\n res.addAll(temp);\n }\n while (i < len-1 && nums[i] == nums[i+1]) {\n //skip duplicated numbers\n i++;\n }\n }\n }\n return res;\n }\n }\n```
1,714
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
84,904
354
class Solution {\n public:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>> total;\n int n = nums.size();\n if(n<4) return total;\n sort(nums.begin(),nums.end());\n for(int i=0;i<n-3;i++)\n {\n if(i>0&&nums[i]==nums[i-1]) continue;\n if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;\n if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue;\n for(int j=i+1;j<n-2;j++)\n {\n if(j>i+1&&nums[j]==nums[j-1]) continue;\n if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;\n if(nums[i]+nums[j]+nums[n-2]+nums[n-1]<target) continue;\n int left=j+1,right=n-1;\n while(left<right){\n int sum=nums[left]+nums[right]+nums[i]+nums[j];\n if(sum<target) left++;\n else if(sum>target) right--;\n else{\n total.push_back(vector<int>{nums[i],nums[j],nums[left],nums[right]});\n do{left++;}while(nums[left]==nums[left-1]&&left<right);\n do{right--;}while(nums[right]==nums[right+1]&&left<right);\n }\n }\n }\n }\n return total;\n }\n };
1,723
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,238
6
# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>> ans;\n sort(nums.begin(), nums.end());\n map<vector<int>, int> mp;\n for(int i=0; i<nums.size()-1; i++) {\n for(int j=i+1; j<nums.size(); j++) {\n int l = j + 1, r = nums.size() - 1; \n while(l < r) {\n long long sum = (long long) nums[i] + nums[j] + nums[l] + nums[r];\n if(sum == target) {\n mp[{nums[i], nums[j], nums[l], nums[r]}]++;\n if(mp[{nums[i], nums[j], nums[l], nums[r]}] == 1) ans.push_back({nums[i], nums[j], nums[l], nums[r]});\n l++;\n r--;\n }\n else if(sum < target) l++;\n else if(sum > target) r--;\n }\n }\n }\n return ans;\n }\n};\n```
1,728
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
867
6
UPVOTE AGAR SAWAL ASAAN KIYA AAPKE LIYE \uD83D\uDE42.\n# Advice\nDONT GO DIRECTLY TO SOLUTION.UNDERSTAND THE FLOW/APPROACH.\nYOU MUST BE KNOWING HOW TO SOLVE TWO SUM PROBLEM .\n\n# Intuition\nI HAVE SOLVED 3SUM USING 2 SUM .THAT\'S WHY I GOT INTUTION TO SOLVE FOUR SOME(\uD83D\uDE01) USING 3 SUM .\n\n# Approach\n1. IN AN ARRAY AT INDEX I, I TAKE THE ARRAY ELEMENT IN FOUR SUM CONSIDERATION IF NOT PREVIOUSLY TAKEN AND STORE IT IN A VARIABLE A=NUMS[I] .THEN ASK THREE SUM TO FIND TARGET-NUMS[I] IN REMAINING ARRAY.\n\n2. AGAIN IN ARRAY AT INDEX I, TAKE THE ARRAY ELEMENT IN FOUR SUM CONSIDERATION IF NOT PREVIOUSLY TAKEN AND STORE IT IN A VARIABLE B=NUMS[I].THEN ASK FOR TWO SUM TO FIND TARGET-NUMS[I] IN REMAINING ARRAY.\n\n3. SIMPLE TWO SUM PROBLEM\uD83D\uDE0E.\n\n```\nwhile(i<j){\n if(target==nums[i]+nums[j]){\n //STORE IN ANS \n ans.push_back({a,b,nums[i],nums[j]});\n // DISTINCT SUBARRAY SHOULD BE INSIDE VECTOR<VECTOR<INT>>ANS.\n i++,j--;\n while(j>i && nums[j]==nums[j+1])j--;\n while(i<j&&nums[i]==nums[i-1])i++;\n }\n else if(nums[i]+nums[j]>target)j--;\n else{\n ++i;\n }\n }\n\n```\nEXAMPLE : LET ARRAY[-2,-2,-1,0,1,1,2,2].TARGET=0.\n![WhatsApp Image 2023-04-21 at 12.06.57.jpg]()\n\n# Code\n```\nclass Solution {\npublic:\n void twosum(vector<int>&nums,int i,long long target,vector<vector<int>>&ans,int a ,int b){\n int n =nums.size();\n int j=n-1;\n\n while(i<j){\n if(target==nums[i]+nums[j]){\n ans.push_back({a,b,nums[i],nums[j]});\n i++,j--;\n while(j>i && nums[j]==nums[j+1])j--;\n while(i<j&&nums[i]==nums[i-1])i++;\n }\n else if(nums[i]+nums[j]>target)j--;\n else{\n ++i;\n }\n }\n return;\n }\n void threesum(vector<vector<int>>&ans,vector<int>& nums,int j,long long target,int a ) {\n int n =nums.size();\n twosum(nums,j+1,target-nums[j],ans,a,nums[j]);\n\n for(int i =j+1;i<n-2;i++){\n if(nums[i]==nums[i-1])continue;\n int b=nums[i];\n twosum(nums,i+1,target-nums[i],ans,a,b);\n }\n return ;\n }\n vector<vector<int>> fourSum(vector<int>& nums, int t) {\n long long target=t;\n vector<vector<int>>ans;\n sort(nums.begin(),nums.end());\n int n =nums.size();\n\n if(n>=4)threesum(ans,nums,1,target-nums[0],nums[0]);\n if(nums[0]>0 && nums[0]>target)return ans;\n\n for(int i=1;i<n-3;i++){\n if(nums[i]==nums[i-1])continue;\n int a=nums[i];\n threesum(ans,nums,i+1,target-nums[i],a);\n }\n return ans ;\n }\n};\n```\nTHANK YOU \nCODE BY:) AMAN MAURYA
1,733
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,998
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```\nimport java.util.*;\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n Arrays.sort(nums);\n List<List<Integer>> q=new ArrayList<>();\n int n=nums.length;\n for(int i=0;i<n-3;i++)\n {\n if(i>0&&nums[i]==nums[i-1])\n {\n continue;\n }\n for(int j=i+1;j<n;j++)\n {\n if(j>i+1&&nums[j]==nums[j-1])\n {\n continue;\n }\n int k=j+1;\n int l=n-1;\n while(k<l)\n {\n long sum = nums[i];\n sum += nums[j];\n sum += nums[k];\n sum += nums[l];\n if(target==sum)\n {\n ArrayList<Integer> al=new ArrayList<>();\n al.add(nums[i]);\n al.add(nums[j]);\n al.add(nums[k]);\n al.add(nums[l]);\n Collections.sort(al);\n q.add(al);\n k++;\n l--;\n\n \n while(k<l&&nums[l]==nums[l+1])\n {\n l--;\n }\n while(k<l&&nums[k]==nums[k-1])\n {\n k++;\n }\n }\n else if(sum<target)\n {\n k++;\n }\n else\n {\n l--;\n }\n }\n }\n }\n\n return q;\n \n }\n \n \n \n}\n```
1,734
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,317
13
\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, long target) {\n vector<vector<int>> ans;\n sort(nums.begin(), nums.end());\n if(nums.size()<4)\n return ans;\n int n=nums.size();\n for(int i=0;i<n-3;i++)\n {\n for(int j=i+1; j<n-2;j++)\n {\n long sum=target-nums[i]-nums[j];\n int l=j+1, r=n-1;\n vector<int> v(4);\n while(l<r)\n {\n if(nums[l]+nums[r]==sum)\n {\n v[0]=nums[i];\n v[1]=nums[j];\n v[2]=nums[l];\n v[3]=nums[r];\n ans.push_back(v);\n while(l<r && v[2]==nums[l])\n l++;\n while(l<r && v[3]==nums[r])\n r--;\n }\n else if(nums[l]+nums[r]<sum)\n l++;\n else\n r--;\n }\n while(j<n-2 && nums[j]==nums[j+1])\n j++;\n }\n while(i<n-3 && nums[i]==nums[i+1])\n i++;\n }\n return ans;\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!!
1,735
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
3,280
56
In this problem we are asked to find not one 4-sum with sum equal to `target`, but all of them. If we were asked to find only one sum, there is `O(n^2)` solution: create array of pairs and then try to find the new pair is equal to `target` minus sums of two numbers. However we need to return all sums and imagine the case `nums = [1, 2, 3, ..., n]`. Then there will be `C_n^4 = O(n^4)` different ways to choose `4` number out of `n` and all sums are in range `[4, 4n]`. It means, that by pingenhole principle there will be some sum which we meet `Omega(n^3)` times, that is `>= alpha*n^3` for some constant alpha.\n\nSo, in general case we can have only `O(n^3)` solution (though with small constant, like 1/6) which allows us to pass problem constraints. The idea is exaclty the same as in other **2Sum** problems: sort numbers, choose `i` and `j` and then use two pointers approach to get solutions.\n\n#### Complexity\nWe need to choose `i` and `j` with complexity `O(n^2)` and then for each choosen pair use two-pointers approach so we have `O(n^3)` total complexity. Space complexity is `O(n)` to keep sorted data.\n\n#### Code\n```python\nclass Solution:\n def fourSum(self, nums, target):\n nums.sort()\n n, ans = len(nums), []\n for i in range(n):\n for j in range(i + 1, n):\n goal = target - nums[i] - nums[j]\n beg, end = j + 1, n - 1\n\n while beg < end:\n if nums[beg] + nums[end] < goal:\n beg += 1\n elif nums[beg] + nums[end] > goal:\n end -= 1\n else:\n ans.append((nums[i], nums[j], nums[beg], nums[end]))\n beg += 1\n end -= 1\n\n return set(ans)\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
1,736
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,588
5
\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target)\n {\n if(nums.size()<4)\n return {};\n set<vector<int>> ans;\n long long int x,sum;\n sort(nums.begin(),nums.end());\n for(int i=0;i<nums.size()-3;i++)\n {\n for(int j=i+1;j<nums.size()-2;j++)\n {\n x=nums[i]+nums[j];\n int p=j+1,q=nums.size()-1;\n while(p<q)\n {\n sum=nums[p]+nums[q];\n if(sum+x==target)\n {\n ans.insert({nums[i],nums[j],nums[p],nums[q]});\n p++;\n }\n else if(sum+x<target)\n p++;\n else if(sum+x>target)\n q--;\n }\n }\n }\n vector<vector<int>> vc(ans.begin(), ans.end());\n return vc;\n }\n};\n```
1,738
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
4,979
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)$$ -->O(n^3)+O(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();\n if(nums==null || nums.length<3)\n return res;\n if(target==-294967296 || target==294967296) return res;\n Arrays.sort(nums);\n int n = nums.length;\n for(int i=0;i<n-3;i++){\n for(int j=i+1;j<n-2;j++){\n int target2 = target-nums[j]-nums[i];\n int front = j+1;\n int back = n-1;\n while(front<back){\n int two_sum =nums[front] +nums[back];\n if(two_sum<target2) front++;\n else if(two_sum>target2) back--;\n else{\n List<Integer> quad = new ArrayList();\n quad.add(nums[i]);\n quad.add(nums[j]);\n quad.add(nums[front]);\n quad.add(nums[back]);\n res.add(quad);\n \n while(front<back && nums[front] == quad.get(2)) ++front;\n while(front<back && nums[back] == quad.get(3)) --back; \n \n }\n }\n while(j+1<n-2 && nums[j+1] == nums[j]) ++j;\n }while(i+1<n-3 && nums[i+1] == nums[i]) ++i;\n } \n return res;\n }\n}\n```
1,741
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
4,157
35
**PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A**\n\n**Intuition:** We will fix two-pointers and then find the remaining two elements using two pointer technique as the array will be sorted at first.\n\n**Approach:**\n* Sort the array, and then fix two pointers, so the remaining sum will be (target \u2013 (nums[i] + nums[j])). \n* Now we can fix two-pointers, one front, and another back, and easily use a two-pointer to find the remaining two numbers of the quad. \n* In order to avoid duplications, we jump the duplicates, because taking duplicates will result in repeating quads. \n* We can easily jump duplicates, by skipping the same elements by running a loop.\n\n```\n// Input => arr[] = [4,3,3,4,4,2,1,2,1,1], target = 9\n// Output => [[1,1,3,4],[1,2,2,4],[1,2,3,3]]\n\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>> res;\n \n if(nums.empty())\n return res;\n \n int n = nums.size();\n \n // Approach requires sorting and 2-pointer approach\n \n // Step1 -> sorting\n sort(nums.begin(),nums.end());\n \n \n // Step2 -> 2-pointer \n for(int i=0; i<n; i++)\n {\n long long int target3 = target - nums[i];\n \n for(int j=i+1; j<n; j++)\n {\n long long int target2 = target3 - nums[j];\n \n int front = j+1;\n int back = n-1;\n \n while(front<back)\n {\n // remaining elements to be found for quad sum\n int two_sum = nums[front] + nums[back];\n \n if(two_sum < target2)\n front++;\n else if(two_sum > target2)\n back--;\n \n else\n {\n // if two_sum == target2\n vector<int> quad(4,0);\n // quad.push_back(nums[i]);\n // quad.push_back(nums[j]);\n // quad.push_back(nums[front]);\n // quad.push_back(nums[back]);\n quad[0] = nums[i];\n quad[1] = nums[j];\n quad[2] = nums[front];\n quad[3] = nums[back];\n \n \n res.push_back(quad);\n \n // Processing the duplicates of number 3\n while(front < back && nums[front] == quad[2]) \n front++;\n \n // Processing the duplicates of number 4\n while(front < back && nums[back] == quad[3]) \n back--;\n }\n \n }\n // Processing the duplicates of number 2\n while(j + 1 < n && nums[j + 1] == nums[j]) \n j++;\n }\n // Processing the duplicates of number 2\n while(i + 1 < n && nums[i + 1] == nums[i]) \n i++;\n }\n \n return res;\n }\n};\n```
1,742
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
3,019
8
\n\n# Approach\n- Sort the input array nums in ascending order. Sorting the array helps in identifying unique quadruplets and allows us to use the two-pointer approach efficiently.\n\n- Iterate through each element in the array using a loop variable i from 0 to the second-to-last index.\n\n- Inside the first loop, check if the current element nums[i] is the same as the previous element nums[i-1]. If they are the same, it means we have already considered this element and generated quadruplets for it. In such cases, we continue to the next iteration to avoid duplicates.\n\n- Start a second loop with a variable j from i+1 to the last index. This loop represents the second element in the quadruplet.\n\n- Similar to step 3, check if the current element nums[j] is the same as the previous element nums[j-1]. If they are the same, continue to the next iteration to avoid duplicates.\n\n- Set two pointers k and l. k starts from j+1 (the next element after j) and moves forward, and l starts from the last index of the array and moves backward.\n\n- Enter a while loop where k is less than l. This loop iterates until k and l cross each other.\n\n- Calculate the sum of the current elements: nums[i] + nums[j] + nums[k] + nums[l].\n\n- If the sum is equal to the target, we have found a valid quadruplet. Create a temporary vector temp and store the elements nums[i], nums[j], nums[k], and nums[l] in it. Add this vector to the ans vector, which stores all the unique quadruplets.\n\n- Move the pointers k and l towards each other. Increment k and decrement l.\n\n- Check for any duplicate elements while moving the pointers. If the next element is the same as the previous one, increment k or decrement l until you find a different element. This step helps in avoiding duplicate quadruplets.\n\n- If the sum is greater than the target, decrement l to decrease the sum.\n\n- If the sum is less than the target, increment k to increase the sum.\n\n- After the second loop ends, continue to the next iteration of the first loop.\n\n- Finally, return the ans vector containing all the unique quadruplets.\n\n# Complexity\n- Time complexity:\nO(n^3)\n\n- Space complexity:\nO(1), O(n) to store the answer\n\n# C++ Code\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>> ans;\n sort(nums.begin(), nums.end());\n for(int i = 0; i< nums.size(); i++){\n if(i>0 && nums[i] == nums[i-1]) continue;\n for(int j = i+1; j< nums.size(); j++){\n if(j> i+1 && nums[j] == nums[j-1]) continue;\n int k = j+1;\n int l = nums.size() - 1;\n while(k<l){\n long long sum = nums[i];\n sum += nums[j];\n sum += nums[k];\n sum += nums[l];\n if(sum == target){\n vector <int> temp = {nums[i], nums[j], nums[k], nums[l]};\n ans.push_back(temp);\n k++;\n l--;\n while(k<l && nums[k] == nums[k-1]) k++;\n while(k<l && nums[l] == nums[l+1]) l--;\n }\n else if(sum > target) l--;\n else k++;\n }\n }\n }\n return ans;\n }\n};\n```\n# JAVA Code\n```\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>> ans = new ArrayList<>();\n Arrays.sort(nums);\n \n for (int i = 0; i < nums.length - 3; i++) {\n if (i > 0 && nums[i] == nums[i - 1]) {\n continue;\n }\n \n for (int j = i + 1; j < nums.length - 2; j++) {\n if (j > i + 1 && nums[j] == nums[j - 1]) {\n continue;\n }\n \n int k = j + 1;\n int l = nums.length - 1;\n \n while (k < l) {\n long sum = (long) nums[i] + nums[j] + nums[k] + nums[l];\n \n if (sum == target) {\n List<Integer> temp = new ArrayList<>();\n temp.add(nums[i]);\n temp.add(nums[j]);\n temp.add(nums[k]);\n temp.add(nums[l]);\n ans.add(temp);\n \n k++;\n l--;\n \n while (k < l && nums[k] == nums[k - 1]) {\n k++;\n }\n \n while (k < l && nums[l] == nums[l + 1]) {\n l--;\n }\n } else if (sum < target) {\n k++;\n } else {\n l--;\n }\n }\n }\n }\n \n return ans;\n }\n}\n```
1,749
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
128,045
225
The first time win over 100%. Basic idea is using subfunctions for 3sum and 2sum, and keeping throwing all impossible cases. O(n^3) time complexity, O(1) extra space complexity.\n\n public List<List<Integer>> fourSum(int[] nums, int target) {\n\t\t\tArrayList<List<Integer>> res = new ArrayList<List<Integer>>();\n\t\t\tint len = nums.length;\n\t\t\tif (nums == null || len < 4)\n\t\t\t\treturn res;\n\n\t\t\tArrays.sort(nums);\n\n\t\t\tint max = nums[len - 1];\n\t\t\tif (4 * nums[0] > target || 4 * max < target)\n\t\t\t\treturn res;\n\n\t\t\tint i, z;\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tz = nums[i];\n\t\t\t\tif (i > 0 && z == nums[i - 1])// avoid duplicate\n\t\t\t\t\tcontinue;\n\t\t\t\tif (z + 3 * max < target) // z is too small\n\t\t\t\t\tcontinue;\n\t\t\t\tif (4 * z > target) // z is too large\n\t\t\t\t\tbreak;\n\t\t\t\tif (4 * z == target) { // z is the boundary\n\t\t\t\t\tif (i + 3 < len && nums[i + 3] == z)\n\t\t\t\t\t\tres.add(Arrays.asList(z, z, z, z));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tthreeSumForFourSum(nums, target - z, i + 1, len - 1, res, z);\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\n\t\t/*\n\t\t * Find all possible distinguished three numbers adding up to the target\n\t\t * in sorted array nums[] between indices low and high. If there are,\n\t\t * add all of them into the ArrayList fourSumList, using\n\t\t * fourSumList.add(Arrays.asList(z1, the three numbers))\n\t\t */\n\t\tpublic void threeSumForFourSum(int[] nums, int target, int low, int high, ArrayList<List<Integer>> fourSumList,\n\t\t\t\tint z1) {\n\t\t\tif (low + 1 >= high)\n\t\t\t\treturn;\n\n\t\t\tint max = nums[high];\n\t\t\tif (3 * nums[low] > target || 3 * max < target)\n\t\t\t\treturn;\n\n\t\t\tint i, z;\n\t\t\tfor (i = low; i < high - 1; i++) {\n\t\t\t\tz = nums[i];\n\t\t\t\tif (i > low && z == nums[i - 1]) // avoid duplicate\n\t\t\t\t\tcontinue;\n\t\t\t\tif (z + 2 * max < target) // z is too small\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (3 * z > target) // z is too large\n\t\t\t\t\tbreak;\n\n\t\t\t\tif (3 * z == target) { // z is the boundary\n\t\t\t\t\tif (i + 1 < high && nums[i + 2] == z)\n\t\t\t\t\t\tfourSumList.add(Arrays.asList(z1, z, z, z));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\ttwoSumForFourSum(nums, target - z, i + 1, high, fourSumList, z1, z);\n\t\t\t}\n\n\t\t}\n\n\t\t/*\n\t\t * Find all possible distinguished two numbers adding up to the target\n\t\t * in sorted array nums[] between indices low and high. If there are,\n\t\t * add all of them into the ArrayList fourSumList, using\n\t\t * fourSumList.add(Arrays.asList(z1, z2, the two numbers))\n\t\t */\n\t\tpublic void twoSumForFourSum(int[] nums, int target, int low, int high, ArrayList<List<Integer>> fourSumList,\n\t\t\t\tint z1, int z2) {\n\n\t\t\tif (low >= high)\n\t\t\t\treturn;\n\n\t\t\tif (2 * nums[low] > target || 2 * nums[high] < target)\n\t\t\t\treturn;\n\n\t\t\tint i = low, j = high, sum, x;\n\t\t\twhile (i < j) {\n\t\t\t\tsum = nums[i] + nums[j];\n\t\t\t\tif (sum == target) {\n\t\t\t\t\tfourSumList.add(Arrays.asList(z1, z2, nums[i], nums[j]));\n\n\t\t\t\t\tx = nums[i];\n\t\t\t\t\twhile (++i < j && x == nums[i]) // avoid duplicate\n\t\t\t\t\t\t;\n\t\t\t\t\tx = nums[j];\n\t\t\t\t\twhile (i < --j && x == nums[j]) // avoid duplicate\n\t\t\t\t\t\t;\n\t\t\t\t}\n\t\t\t\tif (sum < target)\n\t\t\t\t\ti++;\n\t\t\t\tif (sum > target)\n\t\t\t\t\tj--;\n\t\t\t}\n\t\t\treturn;\n\t\t}
1,750
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
4,592
19
\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n vector<vector<int>> output;\n for(int i=0; i<n-3; i++){\n for(int j=i+1; j<n-2; j++){\n long long newTarget = (long long)target - (long long)nums[i] - (long long)nums[j];\n int low = j+1, high = n-1;\n while(low < high){\n if(nums[low] + nums[high] < newTarget){\n low++;\n }\n else if(nums[low] + nums[high] > newTarget){\n high--;\n }\n else{\n output.push_back({nums[i], nums[j], nums[low], nums[high]});\n int tempIndex1 = low, tempIndex2 = high;\n while(low < high && nums[low] == nums[tempIndex1]) low++;\n while(low < high && nums[high] == nums[tempIndex2]) high--;\n }\n }\n while(j+1 < n && nums[j] == nums[j+1]) j++;\n }\n while(i+1 < n && nums[i] == nums[i+1]) i++;\n }\n return output;\n }\n};\n```
1,754
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,788
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```\nList<List<Integer>>ans=new ArrayList<>();\n int n=nums.length;\n Arrays.sort(nums);\n\n for(int i=0;i<n;i++){\n\n if(i!=0 && nums[i]==nums[i-1]) continue;\n\n for(int j=i+1;j<n;j++){\n\n if(j!=i+1 && nums[j]==nums[j-1]) continue;\n\n int k=j+1;\n int l=n-1;\n\n while(k < l){\n long sum=nums[i];\n sum+=nums[j];\n sum+=nums[k];\n sum+=nums[l];\n\n if(sum < target){\n k++;\n }\n else if(sum > target){\n l--;\n }\n else{\n List<Integer>temp=Arrays.asList(nums[i],nums[j],nums[k],nums[l]);\n ans.add(temp);\n k++;\n l--;\n\n while(k < l && nums[k]==nums[k-1]) k++;\n\n while(k < l && nums[l]==nums[l+1]) l--;\n\n }\n }\n } \n\n }\n return ans;\n```
1,756
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
1,611
6
# Approach\nUsing Two Pointer\n\n# Complexity\n- Time complexity:\n$$O(n^3)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n vector<vector<int>> quadruplets;\n for (int i = 0; i < n; i++) {\n if (i != 0 && nums[i] == nums[i-1])\n continue;\n for (int j = i+1; j < n; j++) {\n if (j != i+1 && nums[j] == nums[j-1])\n continue;\n int k = j+1, l = n-1; \n while (k < l) {\n long long sum = nums[i] + nums[j];\n sum += nums[k];\n sum += nums[l];\n if (sum == target) {\n vector<int> temp = {nums[i], nums[j], nums[k], nums[l]};\n quadruplets.push_back(temp);\n k++;\n l--;\n while (k < l && nums[k] == nums[k-1]) k++;\n while (k < l && nums[l] == nums[l+1]) l--;\n } else if (sum > target) {\n l--;\n } else {\n k++;\n }\n } \n }\n }\n return quadruplets;\n }\n};\n```
1,763
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
44,296
217
For the reference, please have a look at my explanation of `3Sum` problem because the algorithm are exactly the same. The link is as blow.\n\n[My 3Sum problem answer][1]\n\nThe key idea is to downgrade the problem to a `2Sum` problem eventually. And the same algorithm can be expand to `NSum` problem.\n\nAfter you had a look at my explanation of `3Sum`, the code below will be extremely easy to understand.\n\n\n class Solution {\n public:\n vector<vector<int> > fourSum(vector<int> &num, int target) {\n \n vector<vector<int> > res;\n \n if (num.empty())\n return res;\n \n std::sort(num.begin(),num.end());\n \n for (int i = 0; i < num.size(); i++) {\n \n int target_3 = target - num[i];\n \n for (int j = i + 1; j < num.size(); j++) {\n \n int target_2 = target_3 - num[j];\n \n int front = j + 1;\n int back = num.size() - 1;\n \n while(front < back) {\n \n int two_sum = num[front] + num[back];\n \n if (two_sum < target_2) front++;\n \n else if (two_sum > target_2) back--;\n \n else {\n \n vector<int> quadruplet(4, 0);\n quadruplet[0] = num[i];\n quadruplet[1] = num[j];\n quadruplet[2] = num[front];\n quadruplet[3] = num[back];\n res.push_back(quadruplet);\n \n // Processing the duplicates of number 3\n while (front < back && num[front] == quadruplet[2]) ++front;\n \n // Processing the duplicates of number 4\n while (front < back && num[back] == quadruplet[3]) --back;\n \n }\n }\n \n // Processing the duplicates of number 2\n while(j + 1 < num.size() && num[j + 1] == num[j]) ++j;\n }\n \n // Processing the duplicates of number 1\n while (i + 1 < num.size() && num[i + 1] == num[i]) ++i;\n \n }\n \n return res;\n \n }\n };\n\n\n [1]:
1,767
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
3,855
6
### **Please Upvote** :D\n##### 1. Brute force approach (TLE - 288/291 passed):\n```\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n int n = nums.length;\n if (n < 4) return new ArrayList<>(); // it\'d still be handled even if we don\'t write this condition\n Arrays.sort(nums);\n\n Set<List<Integer>> ans = new HashSet<>();\n\n for (int i = 0; i < n; i++) \n for (int j = i + 1; j < n; j++) \n for (int k = j + 1; k < n; k++) \n for (int l = k + 1; l < n; l++) \n if (nums[i] + nums[j] + nums[k] + nums[l] == target) \n ans.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));\n\n return new ArrayList(ans);\n }\n}\n\n// TC: O(n * logn) + O(n ^ 4) => O(n ^ 4)\n// SC: O(1) - Ignoring output array\n```\n##### 2. Optimal solution (Two pointers):\nWe iterate using the first for loop and find the remaining 3 elements by the same **[3Sum]()** approach.\n\nOr we can say, we find the first two elements using nested for loops and find the remaining 2 elements by the **[TwoSum]((brute-force-and-optimized))** approach.\n```\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>> ans = new ArrayList<>();\n int n = nums.length;\n\n Arrays.sort(nums);\n\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n\n long target2 = (long) target - (long) nums[i] - (long) nums[j];\n int lo = j + 1, hi = n - 1;\n\n while (lo < hi) {\n int twoSum = nums[lo] + nums[hi];\n\n if (twoSum < target2) lo++;\n else if (twoSum > target2) hi--;\n else {\n List<Integer> quad = Arrays.asList(nums[i], nums[j], nums[lo], nums[hi]);\n ans.add(quad);\n\n while (lo < hi && nums[lo] == quad.get(2)) lo++;\n while (lo < hi && nums[hi] == quad.get(3)) hi--;\n }\n }\n\n while (j + 1 < n && nums[j] == nums[j + 1]) j++;\n }\n\n while (i + 1 < n && nums[i] == nums[i + 1]) i++;\n }\n\n return ans;\n }\n}\n\n// TC: O(n * logn) + O(n ^ 3) => O(n ^ 3)\n// SC: O(1) - ignoring the output array\n```
1,769
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
7,526
48
```\nvector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size(); \n sort(nums.begin() , nums.end()); // sort the array to use the two pointers method\n vector<vector<int>> ans; \n set<vector<int>> store; // to store and remove the duplicate answers\n\t\t\n for(int i = 0 ; i < n; i++){\n\t\t\n for(int j = i + 1; j < n ; j++){\n\t\t\t\n int new_target = target - nums[i] - nums[j];\n \n int x = j+1 , y = n-1;\n \n while(x < y){\n\t\t\t\t\n int sum = nums[x] + nums[y];\n \n if(sum > new_target) y--;\n else if(sum < new_target ) x++;\n else {\n store.insert({nums[i] , nums[j] , nums[x] , nums[y]});\n x++;\n y--;\n };\n }\n }\n }\n\t\t\n for(auto i : store){\n ans.push_back(i); // store the answers in an array(ans)\n }\n\t\t\n return ans;\n }\n```
1,772
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,995
40
<blockquote>\n<b>Disclaimer:</b> By using any content from this post or thread, you release the author(s) from all liability and warranty of any kind. You are free to use the content freely and as you see fit. Any suggestions for improvement are welcome and greatly appreciated! Happy coding!\n</blockquote>\n\n```swift\nclass Solution {\n func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] {\n let len = nums.count\n guard len >= 4 else { return [] }\n \n var result = [[Int]]()\n let sort = nums.sorted()\n \n for a in 0..<(len - 1) where a == 0 || sort[a] != sort[a-1] {\n for b in (a + 1)..<len where b == a + 1 || sort[b] != sort[b-1] {\n var c = b + 1, d = len - 1\n while c < d {\n let val = (a: sort[a], b: sort[b], c: sort[c], d: sort[d])\n let sum = (val.a + val.b + val.c + val.d)\n if sum == target { result.append([val.a,val.b,val.c,val.d]) }\n if sum < target {\n while sort[c] == val.c, c < d { c += 1 }\n } else {\n while sort[d] == val.d, d > b { d -= 1 }\n }\n }\n }\n }\n return result\n }\n}\n```\n\n---\n\n<details>\n<summary>\n<img src="" height="24">\n<b>TEST CASES</b>\n</summary>\n\n<pre>\n<b>Result:</b> Executed 2 tests, with 0 failures (0 unexpected) in 0.010 (0.012) seconds\n</pre>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n func test0() {\n let value = solution.fourSum([1,0,-1,0,-2,2], 0)\n XCTAssertEqual(value, [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]])\n }\n func test1() {\n let value = solution.fourSum([2,2,2,2,2], 8)\n XCTAssertEqual(value, [[2,2,2,2]])\n }\n}\n\nTests.defaultTestSuite.run()\n```\n\n</details>
1,778
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
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
4,684
7
# Intuition\nfix two-pointers and then find the remaining two elements using two pointer technique as the array will be sorted at first.\n\n# Approach\nSort the array, and then fix two pointers, so the remaining sum will be (target \u2013 (nums[i] + nums[j])). Now we can fix two-pointers, one front, and another back, and easily use a two-pointer to find the remaining two numbers of the quad. In order to avoid duplications, we jump the duplicates, because taking duplicates will result in repeating quads. We can easily jump duplicates, by skipping the same elements by running a loop.\n# Complexity\n- Time complexity:\nO(n^3)--> \n2 nested for loops and the front pointer as well as the right pointer (Third nested loop)\n\n- Space complexity:\nO(1)-->\nGenerally the space complexity that is used to return the answer is ignored\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n int n=nums.length;\n Arrays.sort(nums);\n List<List<Integer>> ans=new ArrayList<>();\n if(n==0||n<3){\n return ans;\n }\n if(target==-294967296 || target==294967296){\n return ans;\n }\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n int low=j+1;\n int high=n-1;\n int sum=target-nums[i]-nums[j];\n while(low<high){\n if(nums[low]+nums[high]==sum){\n List<Integer> temp=new ArrayList<>();\n temp.add(nums[i]);\n temp.add(nums[j]);\n temp.add(nums[low]);\n temp.add(nums[high]);\n ans.add(temp);\n while(low<high&&nums[low]==nums[low+1]){\n low++;\n }\n while(low<high&&nums[high]==nums[high-1]){\n high--;\n }\n low++;\n high--;\n }\n else if(nums[low]+nums[high]<sum){\n low++;\n }\n else{\n high--;\n }\n }\n while(j+1<n&&nums[j+1]==nums[j]){\n j++;\n }\n }\n while(i+1<n&&nums[i+1]==nums[i]){\n i++;\n }\n }\n return ans;\n }\n}\n```
1,784
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
3,681
24
**Steps:**\n1. First we store in a map `twoSums` all the pairs of numbers, while the key is their sum and the value is a pair of indices.\n2. For each twoSum, we check if we have its complementary to target in the map too.\n3. If so, we take the lists of indices of the key and the target-key, and pass them to the function `makePairs`.\n4. In `makePairs` we loop through the pairs of indices of both lists and check if the indices are not the same. That\'s because we don\'t want to use the same index twice.\n5. We sort the four results to avoid duplicate fourSums in different orders.\n6. Insert into a set to avoid duplicate fourSums.\n7. Last step is to convert the set into a vector and here we got our result :)\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n nums1 = nums;\n for (int i = 0; i < nums.size(); i++) {\n for (int j = i+1; j < nums.size(); j++) {\n twoSums[nums[i] + nums[j]].push_back({i, j});\n }\n }\n \n for (auto [key, value] : twoSums) {\n int tmp = target - key;\n if (twoSums.find(tmp) != twoSums.end()) makePairs(twoSums[key], twoSums[tmp]);\n }\n \n vector<vector<int>> res(fourSums.begin(), fourSums.end()); \n return res;\n }\n \n void makePairs(vector<pair<int, int>> arr1, vector<pair<int, int>> arr2) {\n for (auto [a, b] : arr1) {\n for (auto [c, d] : arr2) {\n if (a != c && b != c && a != d && b != d) {\n vector<int> tmp = {nums1[a], nums1[b], nums1[c], nums1[d]};\n sort(tmp.begin(), tmp.end());\n fourSums.insert(tmp);\n } \n }\n }\n }\n\nprivate:\n set<vector<int>> fourSums;\n unordered_map<int, vector<pair<int, int>>> twoSums;\n vector<int> nums1;\n};\n```\n**Like it? please upvote!**
1,785
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
54,784
157
public class Solution {\n public List<List<Integer>> fourSum(int[] num, int target) {\n ArrayList<List<Integer>> ans = new ArrayList<>();\n if(num.length<4)return ans;\n Arrays.sort(num);\n for(int i=0; i<num.length-3; i++){\n if(num[i]+num[i+1]+num[i+2]+num[i+3]>target)break; //first candidate too large, search finished\n if(num[i]+num[num.length-1]+num[num.length-2]+num[num.length-3]<target)continue; //first candidate too small\n if(i>0&&num[i]==num[i-1])continue; //prevents duplicate result in ans list\n for(int j=i+1; j<num.length-2; j++){\n if(num[i]+num[j]+num[j+1]+num[j+2]>target)break; //second candidate too large\n if(num[i]+num[j]+num[num.length-1]+num[num.length-2]<target)continue; //second candidate too small\n if(j>i+1&&num[j]==num[j-1])continue; //prevents duplicate results in ans list\n int low=j+1, high=num.length-1;\n while(low<high){\n int sum=num[i]+num[j]+num[low]+num[high];\n if(sum==target){\n ans.add(Arrays.asList(num[i], num[j], num[low], num[high]));\n while(low<high&&num[low]==num[low+1])low++; //skipping over duplicate on low\n while(low<high&&num[high]==num[high-1])high--; //skipping over duplicate on high\n low++; \n high--;\n }\n //move window\n else if(sum<target)low++; \n else high--;\n }\n }\n }\n return ans;\n }\n\nupdated with optimizations and comments
1,789
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,507
18
> **If you\u2019re interested in coding you can join my Discord Server, link in the comment section. Also if you find any mistake please let me know. Thank you!\u2764\uFE0F**\n> \n\n---\n\n## Explanation:\n\n### Solution 01\n\n- First, we\u2019ll sort the array.\n- Take 4 pointers: ***i, j, left, right.***\n- Outer 2 loops for ***i & j.*** We store the remaining value to find in sum variable.\n- Then we try to calculate the ***left+right*** values & if they are equal then push all 4 values to the set.\n- If the value is less than sum then we\u2019ll increase left because array is in sorted order, else we\u2019ll decrease right.\n- **Time complexity:** O(n^3 logn).\n\n---\n\n## Code:\n\n```cpp\n//Solution 01:\n**class Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n set<vector<int>>ans;\n sort(nums.begin(), nums.end());\n int n = nums.size();\n int i=0, j=0, l, r;\n while(i<n){\n j=i+1;\n while(j<n){\n int sum=target-nums[i]-nums[j];\n l=j+1; r=n-1;\n while(l<r){\n int x = nums[l]+nums[r];\n int y = nums[l], z= nums[r] ;\n if(x>sum)\n r--;\n else if(x<sum)\n l++;\n else{\n ans.insert({nums[i],nums[j],nums[l],nums[r]});\n while(l<r && nums[r]==z)r--;\n while(l<r && nums[l]==y)l++;\n }\n }j++;\n \n }i++;\n }\n vector<vector<int>>res(ans.begin(),ans.end());\n return res;\n }\n};**\n```\n\n---\n\n> **Please upvote this solution**\n>
1,793
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
363
6
```cpp\ntypedef long long ll;\n\n\n// Bruteforce | O(n^4) time | O(n) space\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int> &nums, int target) {\n int n = nums.size();\n set<vector<int>> st;\n sort(nums.begin(), nums.end());\n for (int i =0; i < n - 3; i++) {\n for (int j = i + 1; j < n - 2; j++) {\n for (int k = j + 1; k < n - 1; k++) {\n for (int t = k + 1; t < n; t++) {\n if ((ll)nums[i] + nums[j] + nums[k] + nums[t] == (ll)target) {\n vector<int> quad = {nums[i], nums[j], nums[k], nums[t]};\n st.insert(quad);\n }\n }\n }\n }\n }\n vector<vector<int>> res(st.begin(), st.end());\n return res;\n }\n};\n\n\n// Bruteforce | O(n^4) time | O(1) space\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int> &nums, int target) {\n int n = nums.size();\n vector<vector<int>> res;\n sort(nums.begin(), nums.end());\n for (int i =0; i < n - 3; i++) {\n for (int j = i + 1; j < n - 2; j++) {\n for (int k = j + 1; k < n - 1; k++) {\n for (int t = k + 1; t < n; t++) {\n if ((ll)nums[i] + nums[j] + nums[k] + nums[t] == (ll)target) {\n vector<int> quad = {nums[i], nums[j], nums[k], nums[t]};\n res.push_back(quad);\n }\n while (t < n - 1 && nums[t] == nums[t + 1]) t++;\n }\n while (k < n - 1 && nums[k] == nums[k + 1]) k++;\n }\n while (j < n - 1 && nums[j] == nums[j + 1]) j++;\n }\n while (i < n - 1 && nums[i] == nums[i + 1]) i++;\n }\n return res;\n }\n};\n\n\n\n// Optimal | O(n^3 * log(n)) time | O(1) space\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int> &nums, int target) {\n int n = nums.size();\n vector<vector<int>> res;\n sort(nums.begin(), nums.end());\n for (int i = 0; i < n - 3; i++) {\n for (int j = i + 1; j < n - 2; j++) {\n for (int k = j + 1; k < n - 1; k++) {\n ll sumOfThree = (ll)nums[i] + (ll)nums[j] + (ll)nums[k];\n int fourthNum = target - sumOfThree;\n if (binary_search(nums.begin() + k + 1, nums.end(), fourthNum)) {\n vector<int> quad = {nums[i], nums[j], nums[k], fourthNum};\n res.push_back(quad);\n }\n while (k < n - 1 && nums[k] == nums[k + 1]) k++;\n }\n while (j < n - 1 && nums[j] == nums[j + 1]) j++;\n }\n while (i < n - 1 && nums[i] == nums[i + 1]) i++;\n }\n return res;\n }\n};\n\n\n\n// Most Optimal | O(n^3) time | O(1) space\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int> &nums, int target) {\n int n = nums.size();\n vector<vector<int>> res;\n sort(nums.begin(), nums.end());\n for (int i = 0; i < n - 3; i++) {\n for (int j = i + 1; j < n - 2; j++) {\n int l = j + 1, r = n - 1;\n ll remSum = (ll)target - (ll)nums[i] - (ll)nums[j];\n while (l < r) {\n ll sumOfLastTwo = nums[l] + nums[r];\n if (sumOfLastTwo < remSum) l++;\n else if (sumOfLastTwo > remSum) r--;\n else {\n vector<int> quad = {nums[i], nums[j], nums[l], nums[r]};\n res.push_back(quad);\n while (l < r && nums[l] == quad[2]) l++;\n while (l < r && nums[r] == quad[3]) r--;\n }\n }\n while (j < n - 1 && nums[j] == nums[j + 1]) j++;\n }\n while (i < n - 1 && nums[i] == nums[i + 1]) i++;\n }\n return res;\n }\n};\n```
1,799
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.
23,455
118
# Intuition\nwe can find the nth node just by one traversal by using two pointer approach.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTake two dummy nodes, who\u2019s next will be pointing to the head.\nTake another node to store the head, initially,s a dummy node(start), and the next node will be pointing to the head. The reason why we are using this extra dummy node is that there is an edge case. If the node is equal to the length of the LinkedList, then this slow will point to slow\u2019s next\u2192 next. And we can say our dummy start node will be broken and will be connected to the slow next\u2192 next.\n\nStart traversing until the fast pointer reaches the nth node.\n![image.png]()\n\nNow start traversing by one step both of the pointers until the fast pointers reach the end.\n \n![image.png]()\n\nWhen the traversal is done, just do the deleting part. Make slow pointers next to the next of the slow pointer to ignore/disconnect the given node.\n![image.png]()\n\n\nLast, return to the next start.\nDry Run: We will be taking the first example for the dry run, so, the LinkedList is [1,2,3,4,5] and the node which has to be deleted is 2 from the last. For the first time, fast ptr starts traversing from node 1 and reaches 2, as it traverses for node number 2, then the slow ptr starts increasing one, and as well as the fast ptr until it reaches the end.\n\n1st traversal : fast=3, slow=1\n2nd traversal : fast=4, slow=2\n3rd traversal : fast=5, slow=3\nNow, the slow->next->next will be pointed to the slow->next\n\nSo , the new linked list will be [1,2,3,5]\n\nNote that the above approach is provided by Striver on Youtube I highly recommend to checkout his video solutions.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\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 removeNthFromEnd(ListNode head, int n) {\n ListNode start = new ListNode();\n start.next = head;\n ListNode fast = start;\n ListNode slow = start; \n\n for(int i = 1; i <= n; ++i)\n fast = fast.next;\n \n while(fast.next != null)\n {\n fast = fast.next;\n slow = slow.next;\n }\n \n slow.next = slow.next.next;\n \n return start.next;\n }\n}\n```\n\n
1,807
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.
170,871
988
A one pass solution can be done using pointers. Move one pointer **fast** --> **n+1** places forward, to maintain a gap of n between the two pointers and then move both at the same speed. Finally, when the fast pointer reaches the end, the slow pointer will be **n+1** places behind - just the right spot for it to be able to skip the next node.\n\nSince the question gives that **n** is valid, not too many checks have to be put in place. Otherwise, this would be necessary.\n\n public ListNode removeNthFromEnd(ListNode head, int n) {\n \n ListNode start = new ListNode(0);\n ListNode slow = start, fast = start;\n slow.next = head;\n \n //Move fast in front so that the gap between slow and fast becomes n\n for(int i=1; i<=n+1; i++) {\n fast = fast.next;\n }\n //Move fast to the end, maintaining the gap\n while(fast != null) {\n slow = slow.next;\n fast = fast.next;\n }\n //Skip the desired node\n slow.next = slow.next.next;\n return start.next;\n\t}
1,818
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.
14,069
122
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1) .\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\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* removeNthFromEnd(ListNode* head, int n) {\n ListNode* temp=new ListNode();\n temp->next=head;\n\n ListNode* fast=temp;\n ListNode* slow=temp;\n\n for(int i=1;i<=n;i++){\n fast=fast->next;\n }\n\n while(fast->next!=NULL){\n fast=fast->next;\n slow=slow->next;\n }\n\n ListNode* gaya=slow->next;\n slow->next=slow->next->next;\n delete(gaya);\n \n return temp->next;\n }\n};\nif it helps plzz don\'t Forget to upvote it :)\n```
1,819
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.
2,600
13
Please **UPVOTE** if you like my solution!\n\n```\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n int count = 1;\n ListNode c = head;\n while(c.next!=null){\n count++;\n c=c.next;\n }\n \n if(n == count){\n head = head.next;\n return head;\n }\n \n ListNode ln = head;\n int i= 0;\n while(++i<count-n){\n ln = ln.next; \n }\n ln.next = ln.next.next;\n \n return head;\n }\n}\n```
1,838
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.
568
6
# Complexity\n- Time complexity : $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```JAVA []\nclass Solution {\npublic ListNode removeNthFromEnd(ListNode head, int n) {\n if(head == null) return head;\n int k = 0;\n ListNode curr = head;\n for(; curr != null; curr = curr.next) k++;\n k -= n; //to get position of given element from first node\n if(k == 0) return head.next;\n for(curr = head; k > 1; k--, curr = curr.next) ;\n curr.next = curr.next.next; // to remove that node\n return head;\n }\n}\n```\n>>> ## Upvote\uD83D\uDC4D if you find helpful\n
1,839
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.
2,265
9
/* question me dia apko ek linked list di h or bola h Nth node from the end delete krdo mtlb agar linked list h \nL1 = [1,2,3,4,5] or N=2 to last 2nd node delete krdo to vo konsi hogi vo hogi vo node jiska data h 4 to hme 4 ko delete krna h iske lia hmne kya kia hmne ek fast pointer lia jo head pe khada h ek slow ha vo bhi head pe h to phle fast ko jb tk chala lo jb tk fast \'n\' nhi ho jata fir hmne kya kia ek slow pointer lia usko chlao fast ke sath jb tk fast null nhi ho jata (slow bhi ek step , fast bhi ek step) jse hi fast null ho jae to appka slow us position pe ho jisko delete krna h to abb kya kro slow ke next ko krdo slow ke next ka next */\n\n\n\n\nclass Solution {\n\npublic:\n\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n\t\n ListNode* fast = head;\n\t\t\n if(head == NULL)\n\t\t\n return NULL;\n\t\t\t\n ListNode* slow = head;\n \n int count = 1;\n while(n--){\n cout<<fast->val<<" ";\n fast = fast->next;\n }\n if(fast== NULL)\n return slow->next;\n \n while(fast->next != NULL){\n slow = slow->next;\n fast = fast->next;\n }\n slow->next = slow->next->next;\n return head;\n }\n \n};
1,844
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.
5,940
34
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n![Screenshot 2023-03-15 185755.png]()\n\n\n# Code\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 removeNthFromEnd(ListNode head, int n) {\n\n // Create a temporary node and a counter to find the length of the linked list\n ListNode temp = head;\n int count = 0;\n\n // Traverse the linked list and count the number of nodes\n while (temp != null) {\n count++;\n temp = temp.next;\n }\n\n // Calculate the index of the node to be removed from the beginning of the list\n int len = count - n;\n\n // If the first node needs to be removed, update the head and return\n if (len == 0) {\n head = head.next;\n } \n else {\n // Traverse the list until the node before the one to be removed\n ListNode prev = head;\n while (len - 1 != 0) {\n prev = prev.next;\n len--;\n }\n // Remove the node by updating the previous node\'s next pointer\n prev.next = prev.next.next;\n }\n\n // Return the head node of the modified list\n return head;\n }\n}\n```
1,851
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
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,708
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMake a gap of N between two pointers, \nthen increment both pointer one step at a time, until succeeding pointer reaches the end!\nThe preceding pointer will automatically be pointing at \n(LL.size() - n)th position.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n if(!head->next){\n return head->next;\n }\n ListNode* prevHold = NULL;\n ListNode* prev = head;\n ListNode* fwd = head;\n --n;\n while(n--){\n fwd = fwd->next;\n }\n if(!fwd->next){\n return head->next;\n }\n while(fwd->next){\n prevHold = prev;\n prev = prev->next;\n fwd = fwd->next;\n }\n prevHold->next = prev->next;\n delete prev;\n return head;\n }\n};\n```
1,885
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.
539
6
```class Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode* dummynode = new ListNode(0); // creating dummy node;\n\t\t\n\t\t// if head has only one node (base case)\n if(head->next==NULL){\n head=head->next;\n delete(head);\n return dummynode->next;\n }\n dummynode->next=head; // dummy node pointing to head\n ListNode* prev=head; // previous pointer to store previous node\n ListNode* curr=head; // current poninter to point current node\n int count=1;\n while(curr->next!=NULL){\n if(count!=n){\n count++;\n curr=curr->next;\n continue;\n }\n curr=curr->next;\n prev=prev->next;\n }\n \n\t\t\n\t\t//if we have to delete head;\n\t\t\n if(dummynode->next==head && count!=1 && prev==head){\n dummynode->next=head->next;\n return dummynode->next;\n }\n\t\t// traversing till one node begind prev node\n while(head->next!=prev && head!=prev){\n head=head->next;\n }\n head->next=prev->next;\n \n return dummynode->next;\n \n }\n};```
1,891
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.
3,983
45
**Approach**\n- Take two pointers p and q at the head of linked list.\n- Move q pointers by n to the right. Here n = 2.\n- Then move both p and q pointers to right until q reaches the end.\n- Then change pointer of p node to its next to next node.\n- Don\'t forget to delete the last nth node.\n\n**Digram Representation**\n\n![image]()\n\n**C++ Code**\n\n```cpp\nListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *p = head, *q = head;\n while (n--) q = q->next;\n if (!q) return head->next;\n while (q->next) {\n p = p->next;\n q = q->next;\n }\n ListNode* toDelete = p->next;\n p->next = p->next->next;\n delete toDelete;\n return head;\n}\n```\n\n**Related Problems**\n[1. Linked List Cycle ]()\n[2. Linked List Cycle II ]()\n[3. Reorder List ]()\n[4. Sort List ]()\n[5. Swapping Nodes in a Linked List ]()
1,893
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.
9,471
144
ok lets do this!!\nso we are given a linked list and an number \'n\'\nthis n is the number of root from last which needs to be removed!!\nfor example\n1->2->3->4->5->6->7\nn=3\nmeans we have to delete the 3rd node from the last(5th node from the beginning).\nnow that the question is clear !\n\nlets move to the answer!\npiece of advice-whenever you see a linked list removal type question ,always make a dummy node at the beginning!\nanyways!\n\nLOGIC-\n1>we keep two pointer slow and fast(both move one at a time)both initially at start of list(at the dummy node)\n2>we move the fast to n+1 places away from the slow pointer\n3>we then traverse the list we check if fast is equal to null or not,if it is null we know that the slow pointer has reached just one node before the node we need to delete!\n4>then we slow.next=slow.next.next!\n\nshould we do a dry run!\nwhy not!\nsuppose:\n1->2->3->4->5->6\nn=2\nmake a dummy node with val=0;(we call this start)\nso now our list looks like\n0->1->2->3->4->5->6\nslow ,start , fast all are pointing to 0 valued node!\nafter executing step 2 of our algorithm we have \nslow and start still at 0\nbut fast is at node with val 3;\nnow we execute step 3\ndifferent positions of slow and fast is shown below!\n[slow=1,fast=4]->[slow=2,fast=5]->[slow=3,fast=6]->[slow=4,fast=null]\nwow!!slow have reached one node before out target node\nnow just do slow.next=slow.next.next;\n\ndo a couple of dry runs on your own to get the logic!\n```\npublic ListNode removeNthFromEnd(ListNode head, int n) {\n \n ListNode start = new ListNode(0);\n ListNode slow = start, fast = start;\n start.next = head;\n \n \n for(int i=1; i<=n+1; i++) {\n fast = fast.next;\n }\n \n while(fast != null) {\n slow = slow.next;\n fast = fast.next;\n }\n\n slow.next = slow.next.next;\n return start.next;\n}\n```\n\nhope it helps!\nupvote the answer if you like it so that more people can benefit !\n
1,896
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.
296,107
3,419
public boolean isValid(String s) {\n\t\tStack<Character> stack = new Stack<Character>();\n\t\tfor (char c : s.toCharArray()) {\n\t\t\tif (c == '(')\n\t\t\t\tstack.push(')');\n\t\t\telse if (c == '{')\n\t\t\t\tstack.push('}');\n\t\t\telse if (c == '[')\n\t\t\t\tstack.push(']');\n\t\t\telse if (stack.isEmpty() || stack.pop() != c)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn stack.isEmpty();\n\t}
1,902
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.
663
7
# Approach\ncreate a char `stack`, and iterate over individual elements of string **`s`**,\n 1. if character found are opening braces like `\'[\', \'{\' or \'(\'`, then push it into the stack.\n \n 2. else if character found are closing braces like `\']\', \'}\' or \')\'`, then pop out corresponding elements, \n \n - pop `[`, for `]`\n - pop `{`, for `}`\n - pop `(`, for `)`\n\n\n---\n\n\n\n# Code\n```\nclass Solution {\npublic:\n bool isValid(string s) {\n // fast input output stream \n ios_base::sync_with_stdio(false); cin.tie(NULL);\n // creating stack for appending symbols\n stack<char> stc;\n for(auto i : s) {\n // inserting symbols\n if(i == \'(\') stc.push(\'(\');\n else if(i == \'{\') stc.push(\'{\');\n else if(i == \'[\') stc.push(\'[\');\n else {\n // poping out symbols\n if(stc.size() == 0) return false;\n else if(stc.top() == \'(\' && i == \')\') stc.pop();\n else if(stc.top() == \'{\' && i == \'}\') stc.pop();\n else if(stc.top() == \'[\' && i == \']\') stc.pop();\n else return false;\n }\n } \n // check for valid stack\n if(stc.size() == 0) return true;\n return false;\n }\n};\n```\n\n---\n\n\n\n# Complexity\n## Time complexity:\nconsider length of string as n, O(n), time is required to iterate over whole string and O(1) time is required to insert and pop out elements out of stack.\n\n> O(n), final time complexity\n\n## Space complexity:\n\n> O(n), space is used by the stack
1,915
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.
11,534
99
# Intuition\nMy initial approach to solving this problem involves using a stack data structure to keep track of opening brackets. As I iterate through the given string, I\'ll push the corresponding closing bracket onto the stack whenever I encounter an opening bracket. If I encounter a closing bracket, I\'ll check if it matches the top element of the stack. If it does, I\'ll pop the top element from the stack. At the end of the iteration, if the stack is empty, it means all brackets were properly closed, and the string is valid.\n\n# Approach\nI will use a stack to maintain the order of opening brackets encountered. For each character in the given string, I will check if it is an opening bracket (\'(\', \'{\', \'[\'). If it is, I\'ll push the corresponding closing bracket onto the stack. If it\'s a closing bracket, I\'ll compare it with the top element of the stack. If they match, I\'ll pop the top element from the stack. If they don\'t match or the stack is empty, the string is not valid. Finally, if the stack is empty after processing all characters, the string is valid.\n\n\n# Complexity\n- Time complexity: O(n)\n The algorithm iterates through the string once, and each operation inside the loop (stack push, pop, and isEmpty) takes constant time on average.\n- Space complexity: O(n)\n In the worst case, the stack could store all the opening brackets in the string, resulting in a space complexity proportional to the input size.\n\n# Code\n```\nclass Solution {\n public boolean isValid(String s) {\n Stack<Character> stack = new Stack<>();\n\n for (char x : s.toCharArray()\n ) {\n\n if(x==\'(\'){\n \n stack.push(\')\');\n } else if (x==\'{\') {\n stack.push(\'}\');\n \n } else if (x==\'[\') {\n stack.push(\']\');\n } else if (stack.isEmpty() || stack.pop()!=x) {\n\n return false;\n }\n\n }\n\n\n return stack.isEmpty();\n \n }\n}\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]()
1,916
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,168
5
\n# Code\n```\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> st ; \n for (int i = 0 ; i< s.length() ; i++)\n {\n char ch = s[i];\n if (ch == \'(\' || ch == \'{\' || ch == \'[\')\n {\n st.push(ch) ; \n }\n else {\n if (!st.empty())\n {\n char top = st.top() ;\n if ((ch == \')\' && top == \'(\') || \n (ch == \'}\' && top == \'{\') ||\n (ch == \']\' && top == \'[\')) \n {\n st.pop() ;\n }\n else \n {\n return false ; \n }\n }\n else \n {\n return false ;\n }\n }\n }\n if (st.empty())\n {\n return true ; \n }\n return false ;\n }\n};\n```
1,917
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,308
6
# Intuition\nThis problem wants you to know if the given brackets string is balanced or not.\nBalanced brackets looks like this "**( { [ ] } )**" or "**{ }( )[ ]**".\nUnbalanced brackets may look liek this "**( { [ } ] )**".\n\n# Approach\n**1-** We will create a ***stack*** and we will only push to it the opening brackets.\n\n**2-** We will create an ***unordered_map*** that contain opening brackets as the *keys* and their corresponding closing brackets as the *values*.\n\n**3-** We will iterate through our string and check:-\n\u2022 If the *ith char* is an opening bracket we will push it to our stack.\n\u2022 If the char is a closing bracket, is it equal to the top element in the stack (if it is not equal then the brackets aren\'t balanced).\n*Also note that if stack is empty and the char is a closing bracket then it might be something like this **"}"** which isn\'t balanced also.*\n\n**4-** If the last condition is satisfied we pop out the top element (the opening bracket).\n\nWe **return stack.empty()** as we can have an input like **"("** only which will be pushed to the stack then the loop finishes without popping it out or returning false.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# C++ Code\n```\nclass Solution {\npublic:\n bool isValid(string s)\n {\n stack<char> st;\n unordered_map<char, char> closingBrackets = {{\')\', \'(\'}, {\'}\', \'{\'}, {\']\', \'[\'}};\n\n for(char c : s)\n {\n if(c == \'(\' || c == \'{\' || c == \'[\')\n st.push(c);\n else if(st.empty() || st.top() != closingBrackets[c])\n return false;\n else\n st.pop();\n }\n\n return st.empty();\n }\n};\n```
1,918
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.
78,054
828
```\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> st; //taking stack for keep tracking the order of the brackets..\n for(auto i:s) //iterate over each and every elements\n {\n if(i==\'(\' or i==\'{\' or i==\'[\') st.push(i); //if current element of the string will be opening bracket then we will just simply push it into the stack\n else //if control comes to else part, it means that current element is a closing bracket, so check two conditions current element matches with top of the stack and the stack must not be empty...\n {\n if(st.empty() or (st.top()==\'(\' and i!=\')\') or (st.top()==\'{\' and i!=\'}\') or (st.top()==\'[\' and i!=\']\')) return false;\n st.pop(); //if control reaches to that line, it means we have got the right pair of brackets, so just pop it.\n }\n }\n return st.empty(); //at last, it may possible that we left something into the stack unpair so return checking stack is empty or not..\n }\n};\n```\n**If solutions helps you out in any way then don\'t forget to upvote, for such detailed solutions.**\n**Thank you:)**
1,924
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,103
17
# Approach\n1. Firstly we will create a $$vector$$ and $$keep$$ $$pushing$$ $$characters$$ into it\n\n2. We will keep checking if $$does$$ $$it$$ $$form$$ $$a$$ $$pair?$$ if yes then $$remove$$ the $$last$$ $$pushed$$ $$character$$,\n\n3. Create $$IsPair$$ function to Check $$if$$ $$both$$ $$characters$$ $$form$$ $$a$$ $$pair$$\n `\'[\' and \']\' form a pair`\n `\'{\' and \'}\' form a pair`\n `\'[\' ans \']\' form a pair`\n\n4. At last, if we found every completing bracket for every starting bracket, then $$vector$$ $$should$$ $$completely$$ $$become$$ $$empty$$, hence if vector is empty, return $$true,$$ else $$false;$$ \n\n\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n // If they form a pair of matching brackets, {} or () or [], Returns true,\n // Otherwise, it returns false.\n bool isPair(char c1, char c2) {\n return ((c1 == \'{\' && c2 == \'}\') || \n (c1 == \'(\' && c2 == \')\') || \n (c1 == \'[\' && c2 == \']\') );\n }\n\n bool isValid(string s) {\n int n = s.size(); \n // is size of string is odd the return false;\n if(n % 2 == 1) return false;\n // Declaring vector for storing symbols\n vector < char > v;\n for(int i = 0 ; i < n ; i++ ) {\n if(v.size() == 0) {\n v.push_back( s[i] );\n continue;\n }\n // if both characters form a pair, remove the last symbol from vector \n if(isPair( v[v.size() - 1], s[i] )) v.erase(v.begin() + v.size() - 1);\n else v.push_back( s[i] );\n }\n\n // If vector is empty, then only return true, else return false;\n return ( v.size() == 0 );\n }\n};\n```\n\n---\n\n# Complexity \n- Time complexity:\n `O(n)` \n- Space complexity:\n `O(n)` \n\n\n---\n![cat upvote.png]()\n\n\n\n
1,926
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.
38,168
191
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInput string is valid if -: \n- for every opening bracket we have a corresponding closing bracket of the same kind \n- opening brackets of a kind comes before the closing \n- Order of closing is maintained (inner ones are closed before the outer ones)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIf we get any type of opening bracket we push it into the stack\n\nIf we get a bracket of closing type we compare it with the top element of the stack \n\n> opening bracket -> push \nclosing bracket -> compare \n\nWhile comparing with the top of the stack there can be two cases \n1. The stack can be empty \n2. The stack can be non-empty \n\n1.If the stack is not empty \nThen we compare the top element of the stack \n- If the top element and the current element of the string i.e. the closing bracket are of the same type -> `pop the stack `\n\n- If not of the same type then -> `return false` \n\n2.If the stack is empty and we get a closing bracket -> means the string is not valid -> `return false`\n\nIn the end after all the iterations \n- If the stack is empty i.e., all the opening brackets found their corresponding closing brackets and have been popped \nThen we `return true `\n\n- Else `return false`\n\n# Complexity\n- Time complexity:$$O(n)$$ - n is the length of the string \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$ - in the worst case when all the brackets of the string are of opening type our loop will just push all the characters of the string into the stack \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> st ; \n for (int i = 0 ; i< s.length() ; i++)\n {\n char ch = s[i];\n\n // if opening bracket then push into the stack \n if (ch == \'(\' || ch == \'{\' || ch == \'[\')\n {\n st.push(ch) ; \n }\n\n else {\n // if a closing bracket then we compare with the top of the stack \n // while comparing with top of stack we have 2 cases \n // the stack can be empty or the stack is not empty \n if (!st.empty())\n {\n char top = st.top() ;\n if ((ch == \')\' && top == \'(\') || \n (ch == \'}\' && top == \'{\') ||\n (ch == \']\' && top == \'[\')) \n {\n // if matches then pop \n st.pop() ;\n }\n else \n {\n return false ; \n }\n }\n else \n {\n // if stack is empty and we get a closing bracket means the string is unbalanced \n return false ;\n }\n }\n }\n\n // in the end if the stack is empty -- meaning there is no opening bracket present in the stack -- meaning all opening brackets have found their corresponding closing bracket and have been popped then we return trie \n if (st.empty())\n {\n return true ; \n }\n return false ;\n }\n};\n```\n![815a317f-9cdf-46e2-a397-af8869dafa2e_1673498197.3721023 (1).png]()\n
1,927
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.
528
7
# Approach\n- Use a `stack` to store the elements that are not evaluated yet.\n- If (stack is `empty`) push the curr element in stack.\n- If stack is not empty check if the top element of stack is Right combination of the current element then pop out the top element otherwise push it in stack.\n- In last return if stack is empty or not.\n\n# Code\n```\nclass Solution {\npublic:\n\n bool isRightComb(char a, char b){\n if(a==\'(\') return b==\')\';\n \n else if(a==\'{\') return b==\'}\';\n\n else if(a==\'[\') return b==\']\';\n\n return false;\n }\n\n\n bool isValid(string s) {\n stack<char> stk1;\n\n for(int i=0;i<s.size();i++){\n if(!stk1.empty() && isRightComb(stk1.top(),s[i])){\n stk1.pop();\n }else\n stk1.push(s[i]);\n }\n\n return stk1.empty();\n }\n};\n```\n# Please upvote, if you find this helpful \uD83D\uDE4F \n### Thank you in advance ;)
1,928
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,082
9
# Complexity\n- Time complexity: **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isValid(string s) {\n int a=0,b=0,c=0;\n stack<char>st;\n for(int i=0;i<s.size();i++){\n if(st.size()==0)st.push(s[i]);\n else {\n if(s[i]==\'}\'){\n if(st.top()!=\'{\')return false;\n st.pop();\n }\n else if(s[i]==\']\'){\n if(st.top()!=\'[\')return false;\n st.pop();\n }\n else if(s[i]==\')\'){\n if(st.top()!=\'(\')return false;\n st.pop();\n }\n else st.push(s[i]);\n }\n }\n if(st.size())return false;\n return true;\n }\n};\n```\n![upvote (2).jpg]()\n
1,929
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.
904
5
# Please UPVOTE!!!!\n\n![Screenshot 2023-04-10 at 16.02.42.png]()\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nVerifying the input String using Stack DS.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInsert into the stack if the character is opening paranthesis i.e. \'[\', \'{\', \'(\' and check for the valid pair of paranthesis in the TOP of the stack if the character is closing paranthesis \']\', \'}\', \')\'. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(M)\nM is number of opening paranthesis\n0>=M<=N\n\n# Code\n```\nclass Solution {\n public boolean isValid(String s) {\n ArrayList<Character> list = new ArrayList<>();\n for(int i=0;i<s.length();i++){\n char ch = s.charAt(i);\n if(ch==\'(\' || ch==\'[\' || ch==\'{\'){\n list.add(ch);\n }\n else{\n if(list.size()<1){\n return false;\n }\n if(!check(list.get(list.size()-1),ch)){\n return false;\n }\n else{\n list.remove(list.size()-1);\n }\n }\n }\n if(list.size()>0){\n return false;\n }\n return true;\n }\n private boolean check(char ch, char ch1){\n if(ch==\'{\' && ch1==\'}\' || ch==\'(\' && ch1==\')\' || ch==\'[\'&&ch1==\']\'){\n return true;\n }\n return false;\n }\n}\n```
1,930
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.
64,781
190
# Approach\n<!-- Describe your approach to solving the problem. -->\n\n We can use a stack to store characters of the string.\n Then we can do two things:\n 1. if char is open bracket (i.e. \'(\' or \'{\' or \'[\') then push it in stack.\n 2. if char is closed bracket therefore we can check the following conditions:\n\n 1: if \'{\' is before \'}\'.\n 2: if \'(\' is before \')\'.\n 3: if \'[\' is before \']\'.\n\n If any condition is false then return false.\n\nFollow the code below to understand the solution.\n\n **If this solution helped you, give it an up-vote to help others** \n\n# Complexity\n- Time complexity: O(n) where n = length of string.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isValid(String s) {\n\n\n // Create a new stack to store the characters.\n Stack<Character> stack = new Stack<>();\n\n\n // convert string into char array and access the characters using for each loop.\n for(char ch: s.toCharArray())\n {\n // check ch\n switch (ch)\n {\n // open bracket then push it in stack.\n // close bracket then pop the item and compare.\n case \'(\':\n case \'{\':\n case \'[\':\n stack.push(ch);\n break;\n case \')\':\n if(stack.isEmpty() || stack.pop() != \'(\')\n\n // if the stack is empty then it means string have no open bracket.\n // hence it is invalid.\n {\n return false;\n }\n break;\n case \'}\':\n if(stack.isEmpty() || stack.pop() != \'{\')\n {\n return false;\n }\n break;\n case \']\':\n if(stack.isEmpty() || stack.pop() != \'[\')\n {\n return false;\n }\n break;\n }\n }\n\n\n // After the loop we have to check one more condition.\n // return true only if the stack is empty.\n // if stack is not empty that means we have unused brackets.\n\n return stack.isEmpty();\n \n }\n}\n```
1,932
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,207
5
# Approach\nUsing Stack\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> st;\n for (int i = 0; i < s.size(); i++) {\n if (s[i] == \'(\' || s[i] == \'{\' || s[i] == \'[\') {\n st.push(s[i]);\n } else {\n if (st.empty() == false && ((s[i] == \')\' && st.top() == \'(\') || \n (s[i] == \'}\' && st.top() == \'{\') || (s[i] == \']\' && st.top() == \'[\'))) {\n st.pop();\n } else {\n return false;\n }\n } \n }\n return st.empty();\n }\n};\n```
1,934
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,672
13
# Intuition\nWe can use stack for storing all the incoming open brackets and if matching closing bracket comes we need to pop the top of the stack. This is the intial thought\n\n---\n\n# Approach\n1) Initialise Stack.\n2) First thing is to idenity the incoming character is a opening or closing bracket. So i used *String openBrackets = "{(["; with function openBrackets.indexOf(s.charAt(i)) > -1*\n- if **indexOf()** returns anything >-1 that is incoming character was an open bracket\n- else if **indexOf()** return -1 then it was a close bracket as such charcter was not present in string openBrackets.\n3) Once identified, if open bracket push to stack, if closing bracket then handle conditions\n- if stack is empty we cannot push a close bracket first so false\n- if open bracket on stack\'s top doesn\'t matches the closing bracket return false ex \'{\' should match \'}\', \'[\' should match \']\'\n- else remove top charcter from stack\n4) At end of loop if stack is not empty then there are open brackets remaining in the stack so return false, true otherwise\n \n\n---\n\n\n# Complexity\n- Time complexity:\nO(n): As we go through all the characters once in the string.\n\n- Space complexity:\nO(n): In the worst case we can have a max of n characters in stack\n\n---\n\nHope it is easy to understand.\nLet me know if there is something unclear and i can fix it.\n\nOtherwise, please upvote if you like the solution, it would be encouraging\n\n-----\n\n# Code\n```\nclass Solution {\n public boolean isValid(String s) {\n Stack<Character> stack = new Stack<>();\n String openBrackets = "{([";\n for(int i=0; i<s.length(); i++){\n Character temp = s.charAt(i);\n if(openBrackets.indexOf(temp)> -1){\n stack.add(temp);\n }else{\n /* handles all cases for close brackets }]) */\n if(stack.isEmpty()){\n return false;\n }else if(helper(stack.peek())!=temp){\n return false;\n }else{\n stack.pop();\n }\n }\n }\n return stack.empty() ? true : false;\n }\n\n private Character helper(Character left){\n // methode returns what closing bracket should be on comparison with right bracket \n if(left == \'(\'){\n return \')\';\n }else if(left == \'{\'){\n return \'}\';\n }else{\n return \']\';\n }\n }\n}\n```
1,945
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.
1,673
14
# Intuition\nTo determine if a string of parentheses is valid, we need to check if each opening parenthesis has a corresponding closing parenthesis in the correct order. This can be efficiently achieved using a stack data structure. As we iterate through the string, we push opening parentheses onto the stack and pop them when we encounter the corresponding closing parenthesis. If we reach the end of the string with an empty stack, the string is considered valid.\n\n\n# Approach\n1) Initialize a stack to store opening parentheses.\n2) Create a dictionary (or HashMap) to map opening parentheses to their corresponding closing parentheses. This mapping allows us to quickly check if a closing parenthesis matches the top of the stack.\n3) Iterate through the characters of the input string:\n - If the character is an opening parenthesis (\'(\', \'{\', \'[\'), push it onto the stack.\n - If the character is a closing parenthesis (\')\', \'}\', \']\'), check if the stack is empty or if the top of the stack does not match the closing parenthesis in the dictionary. If either condition is met, return `false` since the string is invalid.\n - If the character is a valid closing parenthesis that matches the top of the stack, pop the top element from the stack.\n4) After processing all characters, check if the stack is empty. If it is, return true, indicating that the string is valid. Otherwise, return false as there are unmatched opening parentheses.\n\n\n# Complexity\n`C++ solution complexity:`\n![image.png]()\nNote: Your results may vary due to platform conditions.\n\n\n- Time complexity:\nO(n), where n is the length of the input string.\n\n\n- Space complexity:\nO(n) because of the stack used to store opening parentheses\n# Code\n```C++ []\nclass Solution {\npublic:\n bool isValid(std::string parentheses) {\n std::stack<char> stack;\n std::unordered_map<char, char> dict = {\n {\'(\', \')\'},\n {\'{\', \'}\'},\n {\'[\', \']\'}\n };\n\n for (int i = 0; i < parentheses.length(); i++) {\n if (dict.find(parentheses[i]) != dict.end()) {\n stack.push(parentheses[i]);\n } else if (!stack.empty() && parentheses[i] == dict[stack.top()]) {\n stack.pop();\n } else {\n return false;\n }\n }\n\n return stack.empty();\n }\n};\n```\n```Java []\nclass Solution {\n public boolean isValid(String parentheses) {\n Stack<Character> stack = new Stack<>();\n HashMap<Character, Character> map = new HashMap<>();\n map.put(\'(\', \')\');\n map.put(\'{\', \'}\');\n map.put(\'[\', \']\');\n\n for (int i = 0; i < parentheses.length(); i++) {\n if (map.containsKey(parentheses.charAt(i))) {\n stack.push(parentheses.charAt(i));\n } else if (!stack.isEmpty() && parentheses.charAt(i) == map.get(stack.peek())) {\n stack.pop();\n } else {\n return false;\n }\n }\n\n return stack.isEmpty();\n }\n}\n```\n```C# []\npublic class Solution {\n public bool IsValid(string parentheses) {\n Stack<char> stack = new();\n\n Dictionary<char, char> dict = new(){\n {\'(\', \')\'}, \n {\'{\', \'}\'}, \n {\'[\', \']\'}\n };\n\n for (int i = 0; i < parentheses.Length; i++)\n {\n if(dict.Keys.Contains(parentheses[i]))\n stack.Push(parentheses[i]); \n else if(stack.Count > 0 && parentheses[i] == dict[stack.Peek()])\n stack.Pop();\n else\n return false;\n }\n\n return stack.Count == 0;\n }\n}\n```\n\n## Please, give an upvote and motivate me to do more for the community\n### Keep up the hard work!
1,949
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.
2,221
5
```\nclass Solution:\n def isValid(self, s: str) -> bool:\n stack = []\n \n for c in s:\n match c:\n case \'(\' | \'[\' | \'{\':\n stack.append(c)\n\n case \')\' | \']\' | \'}\':\n if len(stack) is 0:\n return False\n \n top = stack.pop()\n \n if c is \')\' and top is not \'(\':\n return False\n \n elif c is \']\' and top is not \'[\':\n return False\n \n elif c is \'}\' and top is not \'{\':\n return False\n\n case _:\n return False\n \n if len(stack) is not 0:\n return False\n\n return True\n```
1,953
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,824
5
```\nclass Solution {\npublic:\n bool isValid(string s) {\n if(s.length()%2==0)\n {\n stack <char> st;\n st.push(\'#\');\n for(int i=0;i<s.length();i++){\n if(s[i]==\'(\' || s[i]==\'{\'||s[i]==\'[\')\n st.push(s[i]);\n else\n {\n char top = st.top();\n if((s[i]==\')\'&& top==\'(\')||(s[i]==\'}\'&& top==\'{\')||(s[i]==\']\'&& top==\'[\'))\n st.pop();\n else\n return false;\n }\n }\n return (st.top()==\'#\');\n \n }\n return false;\n }\n};\n```
1,954
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.
4,073
30
# **PLEASE UPVOTE \uD83D\uDC4D**\n# Approach\n### - Using stacks, we check if a character is cloasing parantheses and top element of stack is not opening parantheses of same kind, then it is not a valid parantheses.\n### - If the stack is not empty,that is there is an opening parentheses without a corresponding closing parentheses and we can return False, else return true.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> st;\n for(auto i:s)\n {\n // if element is open parantheses, push it in stack\n if(i==\'(\' or i==\'{\' or i==\'[\')\n st.push(i);\n else\n {\n // checking if top element is opening parantheses\n // of same kind as closing parantheses\n if(st.empty() or (st.top()==\'(\' and i!=\')\') or (st.top()==\'{\' and i!=\'}\') or (st.top()==\'[\' and i!=\']\')) return false;\n st.pop();\n }\n }\n // If the stack is not empty,that is there is an opening \n // parentheses without a corresponding closing parentheses and we can return False, else return true.\n return st.empty();\n }\n};\n```\n\n![e2515d84-99cf-4499-80fb-fe458e1bbae2_1678932606.8004954.png]()\n
1,955
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.
8,309
25
```\nclass Solution {\n public boolean isValid(String s) {\n char[] chars = s.toCharArray();\n Stack<Character> stack = new Stack<>();\n for (char element : chars) {\n if (element == \'(\' || element == \'[\' || element == \'{\') {\n stack.push(element);\n continue;\n } else if (stack.empty()) {\n return false;\n }\n char top = stack.pop();\n if (top == \'(\' && element != \')\') {\n return false;\n } else if (top == \'[\' && element != \']\') {\n return false;\n } else if (top == \'{\' && element != \'}\') {\n return false;\n }\n }\n return stack.empty();\n }\n}\n```\n\n![image]()\n
1,968
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.
19,438
83
# Approach\nWe have a few cases where we can immedietly stop looking for validity of the string. \n\nWhenever string has an odd number of items, it\'s impossible to find a pair, so return false.\n\nIf very first item is a closing bracket, we know that we\'ll never find a pair for it, so return false.\n\nNow, the meat of the solution. We need a way to keep track of visited brackets and a way to clear them when their pair has been found. Simple stack should do (in the implementation bellow, I am using an array to act as a stack).\n\nFor simiplicity, let\'s also define a `pairs` map, where opening bracket is a key, and closing bracket is the value.\n\n**Steps:**\n- If lenght of the string is odd, return `false`\n- If first bracket is closing, return `false`\n- If last bracket is an opening one, return `false`\n- Loop over the string\n - If bracket is an opening bracket, push it on top of the stack\n - If bracket is a closing bracket, check if the top of the stack is matching with it\'s pair. \n - If no match is found, it\'s impossible to close the bracket so return `false`\n- Finally, if stack is empty, string is valid\n\n\n# Complexity\n- Time complexity: O(N); we need to, worse case, iterate over every item in the string\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N); because of the usage of stack/array\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @return {boolean}\n */\n\nconst pairs = {\n "(": ")",\n "[": "]",\n "{": "}"\n}\n \nvar isValid = function(s) {\n \n // check if length is an odd number. if it is, return false\n // if there is an odd number, it means that at least one bracket is missing a pair\n if (s.length % 2 === 1) return false\n \n // if the first element is a closing bracket, it doesn\'t matter what follows\n // it will never have a pair\n if (s[0] === "]" || s[0] === ")" || s[0] === "}") return false\n \n // same goes for last element, we are just dealing with opening bracket\n if (s[s.length - 1] === "[" || s[s.length - 1] === "(" || s[s.length - 1] === "{") return false\n \n \n let stack = []\n \n for(let i=0; i<s.length; i++) {\n // if it\'s an opening bracket, push into stack\n // else, assume it\'s closing bracket and check if it matches anything\n if(s[i] === "[" || s[i] === "(" || s[i] === "{") {\n stack.push(s[i])\n } else if (pairs[stack.pop()] !== s[i]) {\n return false\n }\n \n }\n return stack.length === 0\n \n};\n```
1,969
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.
777
5
```\nclass Solution {\npublic:\n bool isValid(string s) { \n stack<char> st;\n \n for(int i=0; i<s.size(); i++){\n if(s[i]==\'(\' || s[i]==\'{\' || s[i]==\'[\'){\n st.push(s[i]);\n }\n else{\n if(st.size()==0)\n return false;\n char c = st.top();\n if(s[i]==\')\' && c!=\'(\')\n return false;\n else if(s[i]==\'}\' && c!=\'{\')\n return false;\n else if(s[i]==\']\' && c!=\'[\')\n return false;\n st.pop();\n }\n }\n if(st.size()==0)\n return true;\n return false;\n }\n};
1,984
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,189
5
```\nclass Solution:\n def isValid(self, s: str) -> bool:\n stack, hm = [], {\'(\': \')\', \'{\': \'}\', \'[\': \']\'}\n for ch in s:\n\t\t\t# open bracket\n if ch in hm: \n stack.append(ch)\n\t\t\t# close bracket\n else: \n if not stack or hm[stack[-1]] != ch: return False\n stack.pop()\n\n return not stack\n```
1,986