question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
lexicographically-minimum-string-after-removing-stars
Easy Java solution using Stacks. Beats 100% in memory ( O(n) ).
easy-java-solution-using-stacks-beats-10-c4qs
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can maintain an ordered map for keeping all the counts of the lexicographically mini
aiqqia
NORMAL
2024-06-02T04:09:51.044881+00:00
2024-06-02T04:09:51.044905+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can maintain an ordered map for keeping all the counts of the lexicographically minimum characters. Keep pushing all the characters onto a stack until you see a *. We we see a *, we can look up the minimum character as the first key of the map and keep popping elements on to another stack until we reach that element. Finally push all the elements back from the temp stack to the main stack.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe use a TreeMap to store the count of the characters in lexicographic order and keep two stacks, st and temp for main string and temporarily popping elements. Finally we convert our stack into a string.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(length^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(length)\n\n# Code\n```\nclass Solution {\n public String clearStars(String s) {\n TreeMap<Character, Integer> map = new TreeMap<>();\n Stack<Character> st = new Stack<>();\n Stack<Character> temp = new Stack<>();\n List<Integer> indices;\n for(int i=0;i<s.length();i++){\n if(s.charAt(i) == \'*\') {\n char ch = map.firstKey();\n while(st.size() > 0 && st.peek() != ch){\n temp.push(st.pop());\n }\n st.pop();\n while(temp.size() > 0) st.push(temp.pop());\n int count = map.get(ch);\n if(count == 1) map.remove(ch);\n else map.put(ch, count-1);\n } else{\n st.push(s.charAt(i));\n map.put(s.charAt(i), map.getOrDefault(s.charAt(i),0)+1);\n }\n }\n String ans = "";\n while(st.size() > 0) ans = st.pop() + ans;\n return ans;\n }\n}\n```
1
0
['Java']
1
lexicographically-minimum-string-after-removing-stars
Using set
using-set-by-aayu_t-c8l0
\n\n# Code\n\nclass Solution {\npublic:\n string clearStars(string s) \n {\n int n = s.length(); \n string r = "";\n set<pair<char,
aayu_t
NORMAL
2024-06-02T04:08:38.918329+00:00
2024-06-02T04:08:38.918353+00:00
6
false
\n\n# Code\n```\nclass Solution {\npublic:\n string clearStars(string s) \n {\n int n = s.length(); \n string r = "";\n set<pair<char, int>> st;\n for(int j = 0; j < n; j++)\n {\n if(s[j] == \'*\')\n {\n pair<char, int> p = *st.begin();\n int index = p.second;\n s[-index] = \'*\';\n st.erase(st.begin());\n }\n else st.insert({s[j], -j});\n }\n for(int i = 0; i < n; i++)\n {\n if(s[i] != \'*\') r += s[i];\n }\n return r;\n }\n};\n```
1
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
JAVA || Stack || 63ms
java-stack-63ms-by-pavan_d_naik-8kus
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
PAVAN_D_NAIK
NORMAL
2024-06-02T04:07:04.144993+00:00
2024-06-02T09:50:22.224271+00:00
46
false
# 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 {\n public String clearStars(String s) {\n int[] f = new int[26];\n List<Stack<Integer>> ind = new ArrayList<>();\n for(int i=0;i<26;i++){\n ind.add(new Stack<>());\n }\n char[] w = s.toCharArray();\n for(int i=0;i<w.length;i++){\n if(w[i]==\'*\'){\n w[i]=\'$\';\n int j=0;\n for(j=0;j<26;j++){\n if(f[j]>0){\n break;\n }\n }\n w[ind.get(j).pop()]=\'$\';\n f[j]--;\n }else{\n f[w[i]-\'a\']++;\n ind.get(w[i]-\'a\').add(i);\n }\n }\n StringBuilder str = new StringBuilder();\n for(char ch:w){\n if(ch!=\'$\'){\n str.append(ch);\n }\n }\n return str.toString();\n }\n \n}\n```
1
0
['Stack', 'Java']
0
lexicographically-minimum-string-after-removing-stars
🔥Greedy || ✅Clean Code || 💯Map + Set⚡
greedy-clean-code-map-set-by-adish_21-gpf4
\n\n# Complexity\n\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n\nclass Solution {\npublic:\n
aDish_21
NORMAL
2024-06-02T04:06:23.560286+00:00
2024-06-02T04:06:23.560323+00:00
114
false
\n\n# Complexity\n```\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n```\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n```\nclass Solution {\npublic:\n string clearStars(string s) {\n int n = s.size();\n map<char, set<int>> mp;\n unordered_set<int> mark;\n for(int i = 0 ; i < n ; i++){\n if(s[i] == \'*\'){\n char ch = mp.begin() -> first;\n auto &s = mp.begin() -> second;\n int val = *s.rbegin();\n mark.insert(val);\n s.erase(val);\n if(!s.size())\n mp.erase(ch);\n }\n else\n mp[s[i]].insert(i);\n }\n string ans = "";\n for(int i = 0 ; i < n ; i++){\n if(s[i] != \'*\' && !mark.contains(i))\n ans += s[i];\n }\n return ans;\n }\n};\n```
1
0
['Ordered Map', 'Ordered Set', 'C++']
1
lexicographically-minimum-string-after-removing-stars
Min Heap | Delete nearest left smallest
min-heap-delete-nearest-left-smallest-by-oz5y
Intuition\nUsing mean heap we can find nearest least smallest element.\n\n\n# Complexity\n- Time complexity: O(nlog(n))\n Add your time complexity here, e.g. O(
rpsingh21
NORMAL
2024-06-02T04:04:58.448519+00:00
2024-06-02T04:39:27.561907+00:00
85
false
# Intuition\nUsing mean heap we can find nearest least smallest element.\n\n\n# Complexity\n- Time complexity: $$O(nlog(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def clearStars(self, s: str) -> str:\n deleted = set()\n heap = []\n for i, ch in enumerate(s):\n if ch == \'*\':\n _, idx = heappop(heap)\n deleted.add(-idx)\n deleted.add(i)\n else:\n heappush(heap, (ch, -i))\n ans = \'\'\n for i, ch in enumerate(s):\n if i not in deleted and ch !=\'*\':\n ans += ch\n return ans\n\n```\n\n![upvote-0.jpeg](https://assets.leetcode.com/users/images/dabdbee4-62cf-49ec-b18c-2f238092a566_1717303165.2118626.jpeg)\n\n
1
0
['Heap (Priority Queue)', 'Python3']
3
lexicographically-minimum-string-after-removing-stars
EZZZYYYY.... CODE.... ⭐
ezzzyyyy-code-by-naakul-uumn
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
naaakul
NORMAL
2024-06-02T04:04:37.406806+00:00
2024-06-02T04:04:37.406844+00:00
139
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String clearStars(String s) {\n StringBuilder ans = new StringBuilder();\n\n int t = 0;\n\n for (int i = 0; i < s.length(); i++) {\n// com.push(s.charAt(i))\n ans.append(s.charAt(i));\n if (s.charAt(i) != \'*\')t++;\n else t--;\n }\n\n if(t == 0)return "";\n\n for (int i = 0; i < ans.length(); i++) {\n if(ans.charAt(i) == \'*\'){\n ans.deleteCharAt(i);\n char temp = \'~\';\n int inTemp = 0;\n for (int j = --i; j > -1; j--) {\n if ((int) ans.charAt(j) < (int) temp){\n inTemp = j;\n temp = ans.charAt(j);\n }\n }\n i--;\n ans.deleteCharAt(inTemp);\n }\n }\n\n return ans.toString();\n }\n}\n```
1
0
['Java']
1
lexicographically-minimum-string-after-removing-stars
Easy HashMap and HashSet Solution
easy-hashmap-and-hashset-solution-by-yas-o49p
IntuitionApproachComplexity Time complexity: O(nlogn) Space complexity: Code
YashMalav_945
NORMAL
2025-04-07T10:05:43.921990+00:00
2025-04-07T10:05:43.921990+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(nlogn) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int n; int findSmallestChar(int &curr_idx,vector<int> &vec,unordered_map<int,set<int>> &mp){ int ch; for(int i=0;i<26;i++){ if(vec[i] > 0){ set<int> &freq = mp[i]; if(*freq.begin() < curr_idx){ vec[i]--; return i; } } } return -1; } string clearStars(string s) { n = s.length(); int last_idx = -1; for(int i=0;i<n;i++){ if(s[i] == '*') last_idx = i; } if(last_idx == -1) return s; vector<int> vec(26,0); unordered_map<int,set<int>> mp; for(int i=0;i<n;i++){ if(s[i] != '*'){ vec[s[i]-'a']++; mp[s[i]-'a'].insert(i); } } for(int i=0;i<n;i++){ if(i > last_idx) break; if(s[i] == '*'){ int ch = findSmallestChar(i,vec,mp); set<int> &st = mp[ch]; auto it = st.lower_bound(i); it--; st.erase(*it); } } vector<vector<int>> v; for(auto &it : mp){ set<int> &st = it.second; for(auto &itr : st){ v.push_back({itr,it.first}); } } sort(v.begin(),v.end()); string result = ""; int m = v.size(); for(int i=0;i<m;i++){ char ch = v[i][1] + 'a'; result += ch; } return result; } }; ```
0
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
My Solution
my-solution-by-hankanggao-7kds
IntuitionApproachComplexity Time complexity: Space complexity: Code
HankangGao
NORMAL
2025-04-04T01:10:00.703374+00:00
2025-04-04T01:10:00.703374+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> ![image.png](https://assets.leetcode.com/users/images/8df8cd64-46a1-47c7-a654-dd721fbf9ea5_1743728992.8674438.png) # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: string clearStars(string s) { vector<vector<int>> indices(26); for(int i = 0; i < s.size(); i++) { int index = s[i] - 'a'; if(s[i] == '*') { for(int j = 0; j < indices.size(); j++) { if(!indices[j].empty()) { indices[j].pop_back(); break; } } } else { indices[index].push_back(i); } } vector<char> new_string(s.size()); for(int i = 0; i < indices.size(); i++) { if(!indices[i].empty()) { for(int j = 0; j < indices[i].size(); j++) { int index = indices[i][j]; new_string[index] = i + 'a'; } } } string ans; for(int i = 0; i < new_string.size(); i++) { if(isalpha(new_string[i])) { ans += new_string[i]; } } return ans; } }; ```
0
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
Eazy Java Solution Using HashMap<>💀...
eazy-java-solution-using-hashmap-by-naze-iagm
IntuitionApproachComplexity Time complexity:O(n) Space complexity:O(n) Code
nazeershaik049
NORMAL
2025-04-02T07:08:36.700859+00:00
2025-04-02T07:08:36.700859+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity:O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String clearStars(String s) { int n = s.length(); HashMap<Character, Stack<Integer>> positionMap = new HashMap<>(); for(char c = 'a'; c <= 'z'; c++){ positionMap.put(c, new Stack<>()); } boolean removeIndex[] = new boolean[n]; for(int i = 0; i < n; i++){ char curr = s.charAt(i); if(curr == '*'){ for(char c = 'a'; c <= 'z'; c++){ if(!positionMap.get(c).isEmpty()){ int removeIdx = positionMap.get(c).pop(); removeIndex[removeIdx] = true; break; } } } else { positionMap.get(curr).push(i); } } StringBuilder result = new StringBuilder(); for(int i = 0; i < n; i++){ if(!removeIndex[i] && s.charAt(i) != '*'){ result.append(s.charAt(i)); } } return result.toString(); } } ```
0
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
Why Not Stack and Why Heap?
why-not-stack-and-why-heap-by-kishan0007-n92q
IntuitionImplementation same as standard Monotonic Stack Problem. Read comments. Everything is explained there.Approach Use a Min-Priority Queue (minPQ) with a
kishan0007
NORMAL
2025-03-22T06:20:28.574917+00:00
2025-03-22T06:20:28.574917+00:00
2
false
# Intuition Implementation same as standard Monotonic Stack Problem. Read comments. Everything is explained there. # Approach 1. Use a Min-Priority Queue (minPQ) with a custom comparator to always store the smallest lexicographical character at the top.If characters are the same, prioritize the rightmost (largest index) character to ensure correct removals. 2. Iterate through the string s. If it's a character, push it into minPQ with its index. If it's a '*', remove the smallest character to its left (top of minPQ) and store its index in a set<int> remove. 3. Build the final result string by skipping characters whose indices are in remove. Keep all other non-'*' characters. # Complexity - Time complexity: O(NlogN) - Space complexity: O(N) # Code ```cpp [] class Solution { public: // Custom comparator for priority queue // To achieve a min-priority queue of type pair<char, int> where the smallest character comes first but, // in the case of equality of characters, the maximum value of integers is prioritized at the top. struct CustomComparator { bool operator()(const pair<char, int>& a, const pair<char, int>& b) { if (a.first == b.first) { // If characters are equal, prioritize the pair with the larger integer return a.second < b.second; } // Otherwise, prioritize the pair with the smaller character return a.first > b.first; } }; string clearStars(string s) { // return lexicographically smallest string. // at the end you want to remove all stars // and some characters. Store the index of characters to be removed // I want a data structure that stores smallest on top and then it gives next smallest. // I will not use stack example "dk**" -> it has k to the right of d. // Neverthless this method is same as Monotonic stack implementation. set<int> remove; // index of characters to be removed in increasing order. priority_queue<pair<char, int>, vector<pair<char, int>>, CustomComparator> minPQ; char min_char = 'z'; for(int i = 0; i<s.size(); i++){ // if it is a char, then push smaller one in stack. if(s[i] != '*'){ minPQ.push({s[i], i}); } else{ // if you encounter '*' then store index of latest smallest character. Then pop it so that next // smallest character(with its index) comes at the top of stack. if(!minPQ.empty()){ remove.insert(minPQ.top().second); minPQ.pop(); } } } vector<int> indices(remove.begin(), remove.end()); // contains indices to be removed int index = 0; string res = ""; for(int i = 0; i<s.size(); i++){ if(s[i] != '*'){ if(index < indices.size() && i == indices[index]){ index++; continue; } else{ // include non '*' char and one whose index is not in indices. res += s[i]; } } } return res; } }; ```
0
0
['Heap (Priority Queue)', 'C++']
0
lexicographically-minimum-string-after-removing-stars
priority_queue solution
priority_queue-solution-by-oldgorain7777-u8jh
Complexity Time complexity:O(Nlogn) Space complexity: Code
oldgorain77779
NORMAL
2025-03-18T07:15:07.335127+00:00
2025-03-18T07:15:07.335127+00:00
1
false
# Complexity - Time complexity:O(Nlogn) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: struct Compare { bool operator()(const pair<char, int>& a, const pair<char, int>& b) { if (a.first != b.first) return a.first > b.first; return a.second < b.second; } }; string clearStars(string s) { unordered_map<int, int> m; priority_queue<pair<char, int>, vector<pair<char, int>>, Compare> pq; for (int i = 0; i < s.size(); i++) { if (s[i] == '*') { cout << i << " "; m[pq.top().second]++; pq.pop(); } else { pq.push({s[i], i}); } } string ss; for (int i = 0; i < s.size(); i++) { if (m.find(i) == m.end() && s[i] != '*') { ss += s[i]; } } return ss; } }; ```
0
0
['String', 'Greedy', 'Heap (Priority Queue)', 'C++']
0
lexicographically-minimum-string-after-removing-stars
EASY C++ SOLUTION USING MIN HEAP
easy-c-solution-using-min-heap-by-suraj_-4t73
IntuitionApproachComplexity Time complexity: Space complexity: Code
suraj_kumar_rock
NORMAL
2025-02-26T18:44:48.777899+00:00
2025-02-26T18:44:48.777899+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { struct mycomp{ bool operator()(pair<char, int>&a, pair<char, int>&b) { if(a.first == b.first) return a.second < b.second; return a.first > b.first; } }; public: string clearStars(string s) { priority_queue<pair<char, int>, vector<pair<char, int>>, mycomp>pq; int n = s.length(); for(int i=0; i<n; i++) { if(s[i] == '*') { if(pq.size() == 0) continue; else { pair<char, int>curr = pq.top(); pq.pop(); s[curr.second] ='#'; } } else { pq.push({s[i], i}); } } string answer = ""; for(auto x: s) { if(x == '#' || x == '*') continue; answer += x; } return answer; } }; ```
0
0
['Heap (Priority Queue)', 'C++']
0
lexicographically-minimum-string-after-removing-stars
C++ | beats 38% | Priority Queue
c-beats-38-priority-queue-by-aryan-ki-co-sc26
Approachso idea is greedy for a star remove rightmost lowest char to its left we maintain heap for it with order a<b<c ... and index order in decreasingfor a st
Aryan-ki-codepanti
NORMAL
2025-02-13T15:41:21.091295+00:00
2025-02-13T15:41:21.091295+00:00
0
false
# Approach <!-- Describe your approach to solving the problem. --> so idea is greedy for a star remove rightmost lowest char to its left we maintain heap for it with order a<b<c ... and index order in decreasing for a star we pop and unmark those indices in end build answer string of marked characters # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(n)$$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(n)$$ # Code ```cpp [] class Rec { public: char ch; int idx; Rec(char a, int b) { ch = a; idx = b; } bool operator<(const Rec& other) const { if (ch != other.ch) return ch > other.ch; return idx < other.idx; } }; class Solution { public: string clearStars(string s) { priority_queue<Rec> pq; int n = s.size(); vector<int> ans(n, 1); for (int i = 0; i < n; i++) { if (s[i] == '*') { // remove ans[pq.top().idx] = 0; ans[i] = 0; pq.pop(); } else { Rec r(s[i], i); pq.push(r); } } string s2; for(int i = 0; i < n; i++) if(ans[i]) s2 += s[i]; return s2; } }; ```
0
0
['C++']
0
lexicographically-minimum-string-after-removing-stars
Go solution, no heap needed
go-solution-no-heap-needed-by-firas5445-7sz0
IntuitionNo need for the heap when you can fetch the smallest item in O(26) given we are only speaking about alphabet chars here.Code
firas5445
NORMAL
2025-02-07T15:40:24.678827+00:00
2025-02-07T15:40:24.678827+00:00
5
false
# Intuition No need for the heap when you can fetch the smallest item in O(26) given we are only speaking about alphabet chars here. # Code ```golang [] /* smallest lexico => means we delete the last occ of the smallest char */ func clearStars(s string) string { occToIndices := [26][]int{} // indices where each char occured, when removing always remove last deleted := map[int]bool{} // to mark when we delete from an index to make life easier for i := range s { if s[i] != '*' { occToIndices[int(s[i]-'a')] = append(occToIndices[int(s[i]-'a')], i) continue } // do O(26) here to check the smallest char and remove it for j := 0; j < 26 ; j++ { if len(occToIndices[j]) > 0 { toDelete := occToIndices[j][len(occToIndices[j])-1] occToIndices[j] = occToIndices[j][:len(occToIndices[j])-1] deleted[toDelete] = true break } } } var res strings.Builder for i := range s { if !deleted[i] && s[i] != '*'{ res.WriteByte(s[i]) } } return res.String() } ```
0
0
['Go']
0
lexicographically-minimum-string-after-removing-stars
Simple Python Solution | Beginner Friendly | Priority Queue
simple-python-solution-beginner-friendly-uz86
Code
imkprakash
NORMAL
2025-01-25T17:11:19.437323+00:00
2025-01-25T17:11:19.437323+00:00
8
false
# Code ```python3 [] class Solution: def clearStars(self, s: str) -> str: s = list(s) heap = [] for i in range(len(s)): if s[i] == '*': s[i] = '' if heap: s[-heap[0][1]] = '' heapq.heappop(heap) else: heapq.heappush(heap, (s[i], -i)) return ''.join(s) ```
0
0
['Python3']
0
lexicographically-minimum-string-after-removing-stars
Easy Python Solution
easy-python-solution-by-karnaraghuvardha-udwk
IntuitionThe problem involves processing a string where stars (*) represent deletions. When a star is encountered, it indicates that the last character before t
karnaraghuvardhanreddy
NORMAL
2025-01-06T19:44:53.180653+00:00
2025-01-06T19:44:53.180653+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem involves processing a string where stars (*) represent deletions. When a star is encountered, it indicates that the last character before the star should be removed. The goal is to process the string by handling each star and updating the string accordingly. The core idea is to: 1.Track the positions of each character in the string. 2.Whenever a star (*) is encountered, remove the most recent character that appeared before it (i.e., the last character that has not already been removed). 3.The challenge lies in efficiently finding and removing the most recent character for each star. # Approach <!-- Describe your approach to solving the problem. --> Track Occurrences of Characters: Use a dictionary last where each key is a character ('a' to 'z'), and the value is a list that stores the positions (indices) where the character appears in the string. This helps us know where each character is located in the string. Process Each Character: Iterate through the string character by character: If the character is not a *, simply record its position in the last dictionary. If the character is a *, check the most recent character in the string that hasn't been removed: Look through the last dictionary to find the most recent character that still has a position recorded in its list. Remove the most recent character by marking its corresponding position as empty in the result list. Pop the last occurrence from the last list for that character to ensure it’s considered removed. Rebuild the String: After processing all characters, convert the result list back into a string, skipping any empty positions (those that have been removed). This approach ensures that the string is processed in a single pass and handles the removal of characters efficiently. # Complexity - Time complexity:O(N*26) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def clearStars(self, s: str) -> str: last={chr(i):[] for i in range(97,123)} ans=list(s) for i in range(len(s)): if s[i]=="*": ans[i]="" for k in "abcdefghijklmnopqrstuvwxyz": if last[k]: ans[last[k][-1]]="" last[k].pop() break else: last[s[i]].append(i) return "".join(ans) ```
0
0
['Greedy', 'Python3']
0
lexicographically-minimum-string-after-removing-stars
Java simple solution time complexity O(NlogN)
java-simple-solution-time-complexity-onl-y76n
IntuitionApproachComplexity Time complexity: Space complexity: Code
Arpitpatel__07
NORMAL
2025-01-04T06:12:10.680007+00:00
2025-01-04T06:12:10.680007+00:00
11
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Pair{ char c; int ind; public Pair(char c,int ind){ this.c=c; this.ind=ind; } } class Solution { public String clearStars(String s) { PriorityQueue<Pair>pq=new PriorityQueue<>((a,b)->{ if(a.c!=b.c){ return a.c-b.c; } else{ return b.ind-a.ind; } }); int i=0; for(char ch:s.toCharArray()){ if(ch=='*'){ if(!pq.isEmpty()){ pq.poll(); } }else{ pq.offer(new Pair(ch,i)); } i++; } ArrayList<Pair>list=new ArrayList<>(); while(!pq.isEmpty()){ list.add(pq.poll()); } Collections.sort(list,(a,b)->a.ind-b.ind); StringBuilder sb=new StringBuilder(); for(Pair num: list){ sb.append(num.c); } return sb.toString(); } } ```
0
0
['Hash Table', 'String', 'Stack', 'Greedy', 'Heap (Priority Queue)', 'Java']
0
lexicographically-minimum-string-after-removing-stars
JAVA || BEGINNERS FRIENDLY||🔥🔥
java-beginners-friendly-by-vikas_333-daoj
IntuitionApproachComplexity Time complexity: Space complexity: Code
vikas_333
NORMAL
2024-12-29T08:49:34.545595+00:00
2024-12-29T08:49:34.545595+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { class p{ char ch; int idx; p(char ch , int idx){ this.ch=ch; this.idx=idx; } } public String clearStars(String s) { char[] word=s.toCharArray(); PriorityQueue<p>pq=new PriorityQueue<>((a,b)->{ if(a.ch==b.ch){ return b.idx-a.idx; } return Character.compare(a.ch,b.ch); }); for(int i=0;i<s.length();i++){ if(word[i]!='*'){ pq.add(new p(word[i],i)); continue; } if(!pq.isEmpty()){ int x=pq.poll().idx; word[x]='*'; } } StringBuilder sb=new StringBuilder(""); for(char c:word){ if(c!='*') sb.append(c); } return sb.toString(); } } ```
0
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
Java Solution || Easy to understand
java-solution-easy-to-understand-by-cute-nmu1
Code
cuteprincess
NORMAL
2024-12-26T15:12:47.826481+00:00
2024-12-26T15:12:47.826481+00:00
4
false
# Code ```java [] class Solution { public String clearStars(String s) { String ans = ""; int freq[] = new int[26]; int j = 0; char x; String substr = ""; for(int i =0; i<26; i++) freq[i] = 0; int len = s.length(); for(int i = 0; i < len; i++){ if(s.charAt(i) == '*'){ while(j<26){ if(freq[j] != 0){ break; } ++j; } x = (char) (j+'a'); int idx = ans.lastIndexOf(x); ans = (ans.substring(0,idx)).concat(ans.substring(idx+1)); freq[j]--; j = 0; }else{ freq[s.charAt(i)-'a']++; ans = ans+s.charAt(i); } } return ans; } } ```
0
0
['Math', 'String', 'String Matching', 'Java']
0
lexicographically-minimum-string-after-removing-stars
✅Easy Java Solution || Beginners Friendly
easy-java-solution-beginners-friendly-by-3n2x
IntuitionApproachComplexity Time complexity: Space complexity: Code
PatanNagoorKhan77
NORMAL
2024-12-20T11:52:37.665140+00:00
2024-12-20T11:52:37.665140+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String clearStars(String s) { PriorityQueue<Pair<Character, Integer>> pq = new PriorityQueue<>( new Comparator<Pair<Character, Integer>>() { public int compare(Pair<Character, Integer> p1, Pair<Character, Integer> p2) { if(Character.compare(p1.getKey(), p2.getKey()) == 0) { return Integer.compare(p2.getValue(), p1.getValue()); } return Character.compare(p1.getKey(), p2.getKey()); } } ); StringBuilder sb = new StringBuilder(s); for(int i=0; i<sb.length(); i++) { if(Character.compare(sb.charAt(i), '*') != 0) { pq.offer(new Pair(sb.charAt(i), i)); } else { if(!pq.isEmpty()) { Pair<Character, Integer> pair = pq.poll(); sb.setCharAt(pair.getValue(), '_'); sb.setCharAt(i, '_'); } } } return sb.toString().replaceAll("_", ""); } } ```
0
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
✅Easy Java Solution || Beginners Friendly
easy-java-solution-beginners-friendly-by-tpge
IntuitionApproachComplexity Time complexity: Space complexity: Code
PatanNagoorKhan77
NORMAL
2024-12-20T11:52:35.444213+00:00
2024-12-20T11:52:35.444213+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String clearStars(String s) { PriorityQueue<Pair<Character, Integer>> pq = new PriorityQueue<>( new Comparator<Pair<Character, Integer>>() { public int compare(Pair<Character, Integer> p1, Pair<Character, Integer> p2) { if(Character.compare(p1.getKey(), p2.getKey()) == 0) { return Integer.compare(p2.getValue(), p1.getValue()); } return Character.compare(p1.getKey(), p2.getKey()); } } ); StringBuilder sb = new StringBuilder(s); for(int i=0; i<sb.length(); i++) { if(Character.compare(sb.charAt(i), '*') != 0) { pq.offer(new Pair(sb.charAt(i), i)); } else { if(!pq.isEmpty()) { Pair<Character, Integer> pair = pq.poll(); sb.setCharAt(pair.getValue(), '_'); sb.setCharAt(i, '_'); } } } return sb.toString().replaceAll("_", ""); } } ```
0
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
java solution
java-solution-by-shaikshaziya-ht0s
IntuitionApproachComplexity Time complexity: Space complexity: Code
ShaikShaziya
NORMAL
2024-12-20T11:52:09.958018+00:00
2024-12-20T11:52:09.958018+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String clearStars(String s) { StringBuilder sb=new StringBuilder(s); PriorityQueue<Pair<Character, Integer>> pq= new PriorityQueue<>( (p,q )->{ int val= Character.compare(p.getKey(), q.getKey()); if(val==0){ return Integer.compare(q.getValue() , p.getValue()); } return val; } ); for(int i=0;i<sb.length();i++){ if(s.charAt(i)!='*'){ pq.offer(new Pair<>(s.charAt(i), i)); } else{ if(!pq.isEmpty()){ Pair<Character, Integer> p=pq.poll(); sb.setCharAt(p.getValue() , '_'); sb.setCharAt(i , '_'); } } } return sb.toString().replaceAll("_", ""); } } ```
0
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
java solution
java-solution-by-shaikshaziya-k05o
IntuitionApproachComplexity Time complexity: Space complexity: Code
ShaikShaziya
NORMAL
2024-12-20T11:37:55.544538+00:00
2024-12-20T11:37:55.544538+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String clearStars(String s) { StringBuilder sb=new StringBuilder(s); PriorityQueue<Pair<Character, Integer>> pq= new PriorityQueue<>( (p,q )->{ int val= Character.compare(p.getKey(), q.getKey()); if(val==0){ return Integer.compare(q.getValue() , p.getValue()); } return val; } ); for(int i=0;i<sb.length();i++){ if(s.charAt(i)!='*'){ pq.offer(new Pair<>(s.charAt(i), i)); } else{ if(!pq.isEmpty()){ Pair<Character, Integer> p=pq.poll(); sb.setCharAt(p.getValue() , '_'); sb.setCharAt(i , '_'); } } } StringBuilder result=new StringBuilder(); int i=0; while(i<sb.length()){ if(sb.charAt(i)!='_'){ result.append(sb.charAt(i)); } i++; } return result.toString(); } } ```
0
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
Lexicographically Minimum String After Removing Star
lexicographically-minimum-string-after-r-4bgn
IntuitionApproachComplexity Time complexity: Space complexity: Code
Naeem_ABD
NORMAL
2024-12-16T15:31:00.981694+00:00
2024-12-16T15:31:00.981694+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc clearStars(s string) string {\n chIdx := make([][]int, 26)\n minCh := 0\n bytes := []byte(s)\n \n for i, v := range(bytes) {\n if v != \'*\' {\n chIdx[v - \'a\'] = append(chIdx[v - \'a\'], i)\n if minCh > int(v - \'a\') {\n minCh = int(v - \'a\')\n }\n } else {\n for minCh < 26 {\n if n := len(chIdx[minCh]); n > 0 {\n minIndex := chIdx[minCh][n - 1]\n chIdx[minCh] = chIdx[minCh][:n - 1]\n bytes[minIndex] = \'*\'\n break\n }\n minCh++\n }\n }\n }\n\n var builder strings.Builder\n for _, v := range(bytes) {\n if v != \'*\' {\n builder.WriteByte(v)\n }\n }\n return builder.String()\n}\n```
0
0
['Go']
0
lexicographically-minimum-string-after-removing-stars
Easy to understand: heap + hashmap; 90% O(N∗Logn)
easy-to-understand-heap-hashmap-90-onlog-yl38
We use heap to get the smallest letter fast and store the indices in the dictionary.\n Describe your approach to solving the problem. \n\n# Complexity\n- Time c
kale111
NORMAL
2024-11-24T01:09:55.477836+00:00
2024-11-24T01:09:55.477865+00:00
4
false
We use heap to get the smallest letter fast and store the indices in the dictionary.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N\u2217Logn)\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```python3 []\nclass Solution:\n def clearStars(self, s: str) -> str:\n res = list(s)\n h = [] # init. heap\n idx = defaultdict(list) # hashmap to store indices\n for i in range(len(s)):\n if s[i] == "*": \n ltr = heapq.heappop(h) # get ltr\n i_del = idx[ltr].pop() # get ind\n res[i_del] = "" # del ltr \n res[i] = "" # del * symbol\n else:\n heapq.heappush(h, s[i]) # save ltr\n idx[s[i]].append(i) # save ind\n return "".join(res)\n```
0
0
['Hash Table', 'Heap (Priority Queue)', 'Python3']
0
lexicographically-minimum-string-after-removing-stars
Easy priority queue solution
easy-priority-queue-solution-by-vikash_k-449m
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
vikash_kumar_dsa2
NORMAL
2024-11-17T08:50:49.508802+00:00
2024-11-17T08:50:49.508831+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string clearStars(string s) {\n priority_queue<pair<char,int>,vector<pair<char,int>>,greater<pair<char,int>>> pq;\n int n = s.size();\n int starCnt = 0;\n for(int i = 0;i<n;i++){\n if(s[i] != \'*\'){\n pq.push({s[i],-i});\n }else{\n char ch = pq.top().first;\n int index = -pq.top().second;\n pq.pop();\n s[i] = s[index] = \'#\';\n }\n }\n string ans = "";\n for(int i = 0;i<n;i++){\n if(s[i] != \'#\'){\n ans += s[i];\n }\n }\n return ans;\n }\n};\n```
0
0
['String', 'Heap (Priority Queue)', 'C++']
0
lexicographically-minimum-string-after-removing-stars
Heap - Java O(N*logN)|O(N)
heap-java-onlognon-by-wangcai20-xjws
Intuition\n Describe your first thoughts on how to solve this problem. \nUse Heap to track the characters lexicographical order. Mark the top one as \' \' when
wangcai20
NORMAL
2024-11-12T02:07:53.939515+00:00
2024-11-12T02:08:20.844788+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse `Heap` to track the characters lexicographical order. Mark the top one as \' \' when encounter \'*\'.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N*logN)$$ \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```java []\nclass Solution {\n public String clearStars(String s) {\n char[] arr = new char[s.length()];\n PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> arr[a] == arr[b] ? b - a : arr[a] - arr[b]);\n int idx = 0;\n for (char ch : s.toCharArray()) {\n if (ch != \'*\') {\n arr[idx++] = ch;\n pq.offer(idx - 1);\n } else {\n while (arr[pq.peek()] == \' \')\n pq.poll();\n arr[pq.peek()] = \' \';\n }\n }\n StringBuilder sb = new StringBuilder();\n for (char ch : arr) {\n if (ch == 0)\n break;\n if (ch != \' \')\n sb.append(ch);\n }\n return sb.toString();\n }\n}\n```
0
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
little bit hard question solved using hashtable and hashset
little-bit-hard-question-solved-using-ha-btmu
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
jeenaSaurabh69
NORMAL
2024-11-04T15:42:00.033330+00:00
2024-11-04T15:42:00.033360+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\no(n)\n\n# Code\n```java []\nclass Solution {\n public String clearStars(String s) {\n HashMap<Character,LinkedList<Integer>> map=new HashMap<>();\n HashSet<Integer> remIndex=new HashSet<>();\n int min=Integer.MAX_VALUE;\n for(int i=0;i<s.length();i++){\n char ch=s.charAt(i);\n if(ch==\'*\'){\n if(!map.isEmpty()){\n char smallest=Collections.min(map.keySet());\n int remLast=map.get(smallest).removeLast();\n remIndex.add(remLast);\n if(map.get(smallest).isEmpty()){\n map.remove(smallest);\n }\n continue;\n }\n \n \n\n }\n map.putIfAbsent(ch,new LinkedList<>());\n map.get(ch).add(i);\n }\n StringBuilder result=new StringBuilder();\n for(int i=0;i<s.length();i++){\n char ch=s.charAt(i);\n if(ch!=\'*\'&&!remIndex.contains(i)){\n result.append(ch);\n }\n \n \n \n }\n \n \n\n\n \n \n \n return result.toString();\n }\n}\n\n```
0
0
['Java']
0
lexicographically-minimum-string-after-removing-stars
____Shivam Gupta_____
shivam-gupta_____-by-shivamgupta90353-jvah
\n\n# Code\ncpp []\nclass Solution {\npublic:\n static bool comp(pair<char, int> a, pair<char, int> b) {\n if (a.first == b.first)\n return
shivamgupta90353
NORMAL
2024-11-03T16:01:48.841784+00:00
2024-11-03T16:01:48.841811+00:00
1
false
\n\n# Code\n```cpp []\nclass Solution {\npublic:\n static bool comp(pair<char, int> a, pair<char, int> b) {\n if (a.first == b.first)\n return a.second < b.second;\n else\n return a.first > b.first;\n }\n string clearStars(string s) {\n priority_queue<pair<char, int>, vector<pair<char, int>>, decltype(&comp)> pq(comp);\n string ans;\n int n = s.size();\n for (int i = 0; i < n; i++) {\n if (s[i] != \'*\') {\n pq.push({s[i], i});\n } else {\n if (!pq.empty()) {\n int idx = pq.top().second;\n pq.pop();\n s[idx] = s[i] = \'#\';\n }\n }\n }\n for (char c : s) {\n if (c != \'#\') {\n ans.push_back(c);\n }\n }\n return ans;\n }\n};\n\n```
0
0
['C++']
0
4sum
Python 140ms beats 100%, and works for N-sum (N>=2)
python-140ms-beats-100-and-works-for-n-s-tdnw
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.\
zhuyinghua1203
NORMAL
2015-08-28T00:12:28+00:00
2018-10-24T07:17:22.153993+00:00
130,136
false
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
660
3
['Python']
95
4sum
My solution generalized for kSums in JAVA
my-solution-generalized-for-ksums-in-jav-b50p
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 th
henryhoo
NORMAL
2016-05-25T10:12:53+00:00
2018-10-25T22:55:46.489886+00:00
88,662
false
#### 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```
520
11
['Java']
46
4sum
✅☑️ Best C++ 3 Solution || Two Pointers || Sorting || Hash Table || Brute Force->Optimize.
best-c-3-solution-two-pointers-sorting-h-u8aa
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 po
its_vishal_7575
NORMAL
2023-02-14T19:32:51.683020+00:00
2023-02-14T19:32:51.683062+00:00
80,587
false
# 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](https://assets.leetcode.com/users/images/0a95fea4-64f4-4502-82aa-41db6d77c05c_1676054939.8270252.jpeg)
511
3
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'C++']
18
4sum
My 16ms c++ code
my-16ms-c-code-by-cx1992-cdqe
class Solution {\n public:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>> total;\n int n =
cx1992
NORMAL
2015-11-02T07:22:57+00:00
2018-10-26T15:48:36.775295+00:00
88,082
false
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 };
376
15
['C++']
61
4sum
[C++/Python] 2 solutions - Clean & Concise - Follow-up: K-Sum
cpython-2-solutions-clean-concise-follow-6pic
✔️ Solution 1: HashSet The idea is to use HashSet to track past elements. We iterate the combinations of nums[i], nums[j], nums[k], and calculate the last numbe
hiepit
NORMAL
2021-07-16T08:00:51.294095+00:00
2025-04-06T10:59:48.451124+00:00
25,205
false
**✔️ Solution 1: HashSet** - The idea is to use `HashSet` to track past elements. - 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]`. - 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. Credit @archit91 for providing C++ version. <iframe src="https://leetcode.com/playground/BsiPbnLs/shared" frameBorder="0" width="100%" height="500"></iframe> Complexity: - Time: `O(N^3)` - Extra Space (Without count output as space): `O(N)` --- **✔️ Solution 2: Sort then Two Pointers** - Sort `nums` in increasing order. - 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](https://leetcode.com/problems/two-sum/)**. - By using two pointers, one points to `left`, the other points to `right`, `goal = target - nums[i] - nums[j]`. - If `nums[left] + nums[right] == goal` - Found a valid quadruplets - Else if `nums[left] + nums[right] > goal` - Sum is bigger than goal, need to decrease sum by `right -= 1` - Else: - Increasing sum by `left += 1`. <iframe src="https://leetcode.com/playground/Dz7F3Sqw/shared" frameBorder="0" width="100%" height="650"></iframe> Complexity: - Time: `O(N^3)` - Extra Space (Without count output as space): `O(sorting)` --- **✔️ Follow-up question: Calculate K-Sum?** <iframe src="https://leetcode.com/playground/KUgSSN93/shared" frameBorder="0" width="100%" height="600"></iframe> Complexity: - Time: `O(NlogN + N^(k-1))`, where `k >= 2`, `N` is number of elements in the array `nums`. - Extra space (Without count output as space): `O(N)` If you think this **post is useful**, I'm happy if you **give a vote**. Any **questions or discussions are welcome!** Thank a lot.
317
19
['Two Pointers', 'C++', 'Python3']
15
4sum
7ms java code win over 100%
7ms-java-code-win-over-100-by-rikimberle-zvwf
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
rikimberley
NORMAL
2015-11-14T16:19:57+00:00
2018-10-25T22:50:45.663149+00:00
131,333
false
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}
234
5
['Java']
63
4sum
4Sum C++ solution with explanation and comparison with 3Sum problem. Easy to understand.
4sum-c-solution-with-explanation-and-com-9ovp
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 ans
kun596
NORMAL
2015-03-06T05:24:32+00:00
2018-08-30T23:25:27.506362+00:00
45,680
false
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]: https://oj.leetcode.com/discuss/23595/share-my-solution-around-50ms-with-explanation-and-comments
223
4
['C++']
20
4sum
Sum MegaPost - Python3 Solution with a detailed explanation
sum-megapost-python3-solution-with-a-det-jf2p
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
peyman_np
NORMAL
2020-07-15T06:59:54.727512+00:00
2020-07-15T22:55:04.652315+00:00
18,675
false
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:](https://leetcode.com/problems/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:](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)** \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**](https://leetcode.com/problems/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](https://leetcode.com/problems/3sum/discuss/7384/My-Python-solution-based-on-2-sum-200-ms-beat-93.37). \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**](https://leetcode.com/problems/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**](https://leetcode.com/problems/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](https://www.***.org/backtracking-introduction/), try to finish [this](https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A) post and do all the examples. \n\nRead my older post first [here](https://leetcode.com/problems/combinations/discuss/729397/python3-solution-with-detailed-explanation). 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](https://leetcode.com/problems/combinations/discuss/729397/python3-solution-with-detailed-explanation)\n\n\n\n================================================================\nFinal note: Please let me know if you found any typo/error/ect. I\'ll try to fix them.
206
0
['Python', 'Python3']
14
4sum
【Video】Simple Solution
video-simple-solution-by-niits-q9fp
\n# Solution Video\n\nhttps://youtu.be/0TjQLNfQ3jc\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n\u25A0
niits
NORMAL
2024-07-19T12:45:02.713071+00:00
2024-07-19T12:45:02.713096+00:00
13,297
false
\n# Solution Video\n\nhttps://youtu.be/0TjQLNfQ3jc\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 6,628\nThank you for your support!\n\n---\n\n```python []\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n nums.sort()\n res = []\n\n for i in range(len(nums) - 3):\n # skip duplicate starting values\n if i > 0 and nums[i] == nums[i-1]:\n continue\n \n for j in range(i+1, len(nums) - 2):\n # skip duplicate starting values\n if j > i + 1 and nums[j] == nums[j-1]:\n continue\n left, right = j + 1, len(nums) - 1\n\n while left < right:\n four_sum = nums[i] + nums[j] + nums[left] + nums[right]\n if four_sum == target:\n res.append([nums[i], nums[j], nums[left], nums[right]])\n left += 1\n right -= 1\n\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 elif four_sum < target:\n left += 1\n else:\n right -= 1\n return res\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[][]}\n */\nvar fourSum = function(nums, target) {\n const result = [];\n\n if (nums == null || nums.length < 4) {\n return result;\n }\n\n nums.sort((a, b) => a - b);\n const len = nums.length;\n \n for (let i = 0; i < len - 3; i++) {\n if (i > 0 && nums[i] == nums[i-1]) {\n continue;\n }\n for (let j = i+1; j < len - 2; j++) {\n if (j > i+1 && nums[j] == nums[j-1]) {\n continue;\n }\n let left = j + 1;\n let right = len - 1;\n while (left < right) {\n const sum = nums[i] + nums[j] + nums[left] + nums[right];\n \n if (sum == target) {\n result.push([nums[i], nums[j], nums[left], nums[right]]);\n\n while (left < right && nums[left] == nums[left+1]) {\n left++;\n }\n\n while (left < right && nums[right] == nums[right-1]) {\n right--;\n }\n\n left++;\n right--;\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n }\n }\n }\n\n return result\n};\n```\n\n---\n\n\n\n# \u2B50\uFE0F Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n# \u2B50\uFE0F Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n# \u2B50\uFE0F My previous video\n#28 - Longest Consecutive Sequence \n\nhttps://youtu.be/PRVmb_7u6fo
182
0
['Python3', 'JavaScript']
1
4sum
Clean accepted java O(n^3) solution based on 3sum
clean-accepted-java-on3-solution-based-o-bb48
public class Solution {\n public List<List<Integer>> fourSum(int[] num, int target) {\n ArrayList<List<Integer>> ans = new ArrayList<>();\n if(
casualhero
NORMAL
2015-04-20T05:57:57+00:00
2018-10-26T22:19:56.048360+00:00
56,657
false
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
179
19
['Java']
39
4sum
C++ - Easiest Beginner Friendly Sol || Set + Two Pointer Approach || O(n^3) time and O(n) space
c-easiest-beginner-friendly-sol-set-two-slk8t
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 fir
singhabhinash
NORMAL
2023-01-28T16:34:39.235533+00:00
2023-01-28T16:34:39.235578+00:00
14,864
false
# 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** https://www.linkedin.com/in/abhinash-singh-1b851b188\n\n![57jfh9.jpg](https://assets.leetcode.com/users/images/c2826b72-fb1c-464c-9f95-d9e578abcaf3_1674104075.4732099.jpeg)\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)$$ -->
89
0
['Two Pointers', 'Python', 'C++', 'Java']
8
4sum
On average O(n^2) and worst case O(n^3) java solution by reducing 4Sum to 2Sum
on-average-on2-and-worst-case-on3-java-s-k4pq
Basic idea is to reduce the 4Sum problem to 2Sum one. In order to achieve that, we can use an array (size of n^2) to store the pair sums and this array will act
fun4leetcode
NORMAL
2015-04-27T23:30:17+00:00
2018-10-26T08:28:03.959799+00:00
21,458
false
Basic idea is to reduce the 4Sum problem to 2Sum one. In order to achieve that, we can use an array (size of n^2) to store the pair sums and this array will act as the array in 2Sum case (Here n is the size of the original 1D array and it turned out that we do not even need to explicitly use the n^2 sized array ). We also use a hashmap to mark if a pair sum has been visited or not (the same as in the 2Sum case). The tricky part here is that we may have multiple pairs that result in the same pair sum. So we will use a list to group these pairs together. For every pair with a particular sum, check if the pair sum that is needed to get the target has been visited. If so, further check if there is overlapping between these two pairs. If not, record the result.\n\nTime complexity to get all the pairs is O(n^2). For each pair, if the pair sum needed to get the target has been visited, the time complexity will be O(k), where k is the maximum size of the lists holding pairs with visited pair sum. Therefore the total time complexity will be O(k*n^2). Now we need to determine the range of k. Basically the more distinct pair sums we get, the smaller k will be. If all the pair sums are different from each other, k will just be 1. However, if we have many repeated elements in the original 1D array, or in some extreme cases such as the elements form an arithmetic progression, k can be of the order of n (strictly speaking, for the repeated elements case, k can go as high as n^2, but we can get rid of many of them). On average k will be some constant between 1 and n for normal elements distribution in the original 1D array. So on average our algorithm will go in O(n^2) but with worst case of O(n^3). Here is the complete code in java:\n\n public List<List<Integer>> fourSum(int[] num, int target) {\n Arrays.sort(num);\n \n Map<Integer, List<int[]>> twoSumMap = new HashMap<>(); // for holding visited pair sums. All pairs with the same pair sum are grouped together\n Set<List<Integer>> res = new HashSet<>(); // for holding the results\n \n for (int i = 0; i < num.length; i++) {\n \t// get rid of repeated pair sums\n if (i > 1 && num[i] == num[i - 2]) continue;\n \t\n for (int j = i + 1; j < num.length; j++) {\n // get rid of repeated pair sums\n if (j > i + 2 && num[j] == num[j - 2]) continue;\n\n // for each pair sum, check if the pair sum that is needed to get the target has been visited. \t\n if (twoSumMap.containsKey(target - (num[i] + num[j]))) { \n // if so, get all the pairs that contribute to this visited pair sum.\n \tList<int[]> ls = twoSumMap.get(target - (num[i] + num[j]));\n \t\t\n \tfor (int[] pair : ls) {\n \t // we have two pairs: one is indicated as (pair[0], pair[1]), the other is (i, j).\n \t // we first need to check if they are overlapping with each other.\n \t int m1 = Math.min(pair[0], i); // m1 will always be the smallest index\n int m2 = Math.min(pair[1], j); // m2 will be one of the middle two indices\n int m3 = Math.max(pair[0], i); // m3 will be one of the middle two indices\n int m4 = Math.max(pair[1], j); // m4 will always be the largest index\n \n if (m1 == m3 || m1 == m4 || m2 == m3 || m2 == m4) continue; // two pairs are overlapping, so just ignore this case\n \t\t \n \t\t res.add(Arrays.asList(num[m1], num[Math.min(m2, m3)], num[Math.max(m2, m3)], num[m4])); // else record the result\n \t}\n }\n \n // mark that we have visited current pair and add it to the corrsponding pair sum group.\n // here we've encoded the pair indices i and j into an integer array of length 2.\n twoSumMap.computeIfAbsent(num[i] + num[j], key -> new ArrayList<>()).add(new int[] {i, j});\n }\n }\n \n return new ArrayList<List<Integer>>(res);\n }
65
1
[]
15
4sum
Easy to understand python Solution
easy-to-understand-python-solution-by-vi-pbnx
\nclass Solution:\n def fourSum(self, nums, target):\n """\n :type nums: List[int]\n :type target: int\n :rtype: List[List[int]]\
vidyasagar93
NORMAL
2018-05-04T06:43:10.602436+00:00
2018-10-04T08:05:35.192657+00:00
10,025
false
```\nclass Solution:\n def fourSum(self, nums, target):\n """\n :type nums: List[int]\n :type target: int\n :rtype: List[List[int]]\n """\n d = dict()\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n sum2 = nums[i]+nums[j]\n if sum2 in d:\n d[sum2].append((i,j))\n else:\n d[sum2] = [(i,j)]\n \n result = set()\n for key in d:\n value = target - key\n if value in d:\n list1 = d[key]\n list2 = d[value]\n for (i,j) in list1:\n for (k,l) in list2:\n if i!=k and i!=l and j!=k and j!=l:\n flist = [nums[i],nums[j],nums[k],nums[l]]\n flist.sort()\n result.add(tuple(flist))\n return list(result)\n```
57
0
[]
21
4sum
[Python] O(n^3) and why we can not do better, explained
python-on3-and-why-we-can-not-do-better-uhqxj
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: c
dbabichev
NORMAL
2021-07-16T08:21:57.576551+00:00
2021-07-16T08:21:57.576582+00:00
3,542
false
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!**
56
0
[]
7
4sum
C++ short , easy , two pointers solution
c-short-easy-two-pointers-solution-by-su-4550
\nvector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size(); \n sort(nums.begin() , nums.end()); // sort the array to u
suryanshusingh
NORMAL
2021-07-26T02:22:12.170597+00:00
2021-07-26T02:26:24.527463+00:00
7,865
false
```\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```
49
1
['Two Pointers', 'C']
6
4sum
My C++ solution using hashtable
my-c-solution-using-hashtable-by-asafeat-bx1f
My idea is to sort num first, then build a hashtable with the key as the sum of the pair and the value as a vector storing all pairs of index of num that havin
asafeather
NORMAL
2014-10-02T22:20:58+00:00
2018-10-25T16:40:10.004745+00:00
17,468
false
My idea is to sort num first, then build a hashtable with the key as the sum of the pair and the value as a vector storing all pairs of index of num that having the same sum. In this way, all elements stored in hashtable has a order that duplicate pairs are neighbors. Therefore scanning the vector in the hashtable we only put non duplicate elements into the final answer vvi.\n\nIs this method O(n^2) ? or Does anyone can improve it to O(n^2);\n\n\n\n class Solution{ //using hashtable, avg O(n^2)\n \n public:\n \n vector<vector<int> > fourSum(vector<int> &num, int target){\n vector<vector<int> > vvi;\n int n = num.size();\n if(n < 4) return vvi;\n \n sort(num.begin(), num.end()); \n unordered_map<int, vector<pair<int, int>> > mp;\n for(int i = 0; i < n; i++){\n for(int j = i + 1; j < n; j++){\n mp[num[i]+num[j]].push_back(make_pair(i,j));\n }\n }\n \n for(int i = 0; i < n; i++){\n if(i>0 && num[i] == num[i-1]) continue;\n for(int j = i + 1; j < n; j++){\n if(j > i + 1 && num[j] == num[j-1]) continue;\n int res = target - num[i] - num[j];\n if(mp.count(res)){\n for(auto it = mp[res].begin(); it != mp[res].end(); it++){\n int k = (*it).first, l = (*it).second;\n if(k > j){ // k>j make sure that the second pair has bigger values than the first pair.\n if(!vvi.empty() && num[i]==vvi.back()[0] && num[j]==vvi.back()[1]\n && num[k]==vvi.back()[2] && num[l] == vvi.back()[3]){\n continue; //if the obtained 4 elements are the same as previous one continue to next\n }\n vector<int> vi={num[i], num[j], num[k], num[l]};\n vvi.push_back(vi);\n } // if k>j\n \n }//for it\n }//if\n }// forj\n }//for i\n return vvi;\n }\n };
45
2
[]
11
4sum
✅ [Accepted] Solution for Swift
accepted-solution-for-swift-by-asahiocea-7b1v
\nDisclaimer: 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 cont
AsahiOcean
NORMAL
2021-07-10T06:47:24.309453+00:00
2022-04-28T10:33:05.831604+00:00
3,313
false
<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="https://git.io/JDblm" 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>
40
0
['Swift']
0
4sum
20-line, elegant accepted JAVA solution using Backtracking.
20-line-elegant-accepted-java-solution-u-gmic
The key idea is using backtracking. But before each step, I checked the eligibility of i-th element in the array before adding it to the subset list. Basically
candle309
NORMAL
2017-08-01T23:25:58.014000+00:00
2018-10-20T03:44:29.894346+00:00
4,453
false
The key idea is using backtracking. But before each step, I checked the eligibility of i-th element in the array before adding it to the subset list. Basically a lower and an upper boundaries were added to each backtracking step.\n```\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>> ans = new ArrayList<List<Integer>>();\n if(nums == null || nums.length == 0) return ans;\n List<Integer> list = new ArrayList<>();\n Arrays.sort(nums);\n getSum(nums, 0, target, ans, list, 0);\n return ans;\n }\n private void getSum(int[] nums, int sum, int target, List<List<Integer>> ans, List<Integer> list, int pos){\n if(list.size() == 4 && sum == target && !ans.contains(list)){\n ans.add(new ArrayList<>(list)); return;\n }else if(list.size() == 4) return;\n for(int i = pos; i < nums.length; i++){\n if(nums[i] + nums[nums.length - 1] * (3 - list.size()) + sum < target) continue;\n if(nums[i] * (4 - list.size()) + sum > target) return;\n list.add(nums[i]);\n getSum(nums, sum + nums[i], target, ans, list, i + 1);\n list.remove(list.size() - 1);\n }\n }\n```
36
0
[]
12
4sum
✅C++ || BEATS 96% || OPTIMIZED
c-beats-96-optimized-by-ayushsenapati123-a0se
PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A\n\nIntuition: We will fix two-pointers and then find the remaining two elements using tw
ayushsenapati123
NORMAL
2022-07-16T14:22:55.568368+00:00
2022-07-16T14:22:55.568413+00:00
4,644
false
**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```
35
0
['C', 'C++']
4
4sum
JavaScript using 4 pointers beats 96%
javascript-using-4-pointers-beats-96-by-oqgpx
\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[][]}\n */\nvar fourSum = function(nums, target) {\n nums.sort((a, b) => a - b
control_the_narrative
NORMAL
2020-04-16T00:10:10.662395+00:00
2020-04-19T04:10:36.878353+00:00
5,324
false
```\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[][]}\n */\nvar fourSum = function(nums, target) {\n nums.sort((a, b) => a - b);\n const result = []\n \n for(let i = 0; i < nums.length - 3; i++) {\n for(let j = i + 1; j < nums.length - 2; j++) {\n let low = j + 1;\n let high = nums.length - 1\n\n while(low < high) {\n const sum = nums[i] + nums[j] + nums[low] + nums[high];\n if(sum === target) {\n result.push([nums[i], nums[j], nums[low], nums[high]])\n while(nums[low] === nums[low + 1]) low++;\n while(nums[high] === nums[high - 1]) high--;\n low++;\n high--;\n } else if(sum < target) {\n low++\n } else {\n high--\n }\n } \n while(nums[j] === nums[j + 1]) j++;\n } \n while(nums[i] === nums[i + 1]) i++;\n }\n return result\n};\n```
34
0
['JavaScript']
1
4sum
*Java* a little bit faster than other common methods (9ms, beats 95%)
java-a-little-bit-faster-than-other-comm-5smc
To avoid duplicate list items, I skip unnecessary indices at two locations:\n\n - one at the end of the outer loop (i-loop)\n - the other at the end of the inne
elementnotfoundexception
NORMAL
2016-01-07T02:15:59+00:00
2018-10-16T03:14:53.739879+00:00
10,208
false
To avoid duplicate list items, I skip unnecessary indices at two locations:\n\n - one at the end of the outer loop (`i-loop`)\n - the other at the end of the inner loop (`j-loop`). \n\n\nTo avoid useless computations, the following is kind of critical:\n\n - the function `return` immediately when `nums[i]*4 > target`\n - the inner loop `break` immediately when `nums[j]*4 < target`. \n\nThese two lines save quite some time due to the set up of the test cases in OJ.\n\n public class Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>> list = new ArrayList<List<Integer>>();\n Arrays.sort(nums);\n int second = 0, third = 0, nexti = 0, nextj = 0;\n for(int i=0, L=nums.length; i<L-3; i++) {\n if(nums[i]<<2 > target) return list; // return immediately\n for(int j=L-1; j>i+2; j--) {\n if(nums[j]<<2 < target) break; // break immediately\n int rem = target-nums[i]-nums[j];\n int lo = i+1, hi=j-1;\n while(lo<hi) {\n int sum = nums[lo] + nums[hi];\n if(sum>rem) --hi;\n else if(sum<rem) ++lo;\n else {\n list.add(Arrays.asList(nums[i],nums[lo],nums[hi],nums[j]));\n while(++lo<=hi && nums[lo-1]==nums[lo]) continue; // avoid duplicate results\n while(--hi>=lo && nums[hi]==nums[hi+1]) continue; // avoid duplicate results\n }\n }\n while(j>=1 && nums[j]==nums[j-1]) --j; // skip inner loop\n }\n while(i<L-1 && nums[i]==nums[i+1]) ++i; // skip outer loop\n }\n return list;\n }\n }
34
0
['Java']
4
4sum
GENERAL BACKTRACKING SOLUTION FOR N-SUM SERIES QUESTIONS. CHECK IT OUT!! [CPP/JAVA/PYTHON]
general-backtracking-solution-for-n-sum-ihfp4
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
Dominating_
NORMAL
2023-09-30T09:18:27.782087+00:00
2023-09-30T09:18:27.782105+00:00
3,960
false
# 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](https://assets.leetcode.com/users/images/2fedb1ea-428b-40ea-a6f2-166939b773d4_1696065027.8550835.jpeg)\n\n
31
0
['Backtracking', 'Python', 'C++', 'Java']
2
4sum
TwoSum+twoSum == fourSum, a simple python solution
twosumtwosum-foursum-a-simple-python-sol-j926
class Solution:\n # @return a list of lists of length 4, [[val1,val2,val3,val4]]\n def fourSum(self, num, target):\n two_sum = collections.defaultd
tusizi
NORMAL
2015-02-20T11:44:35+00:00
2015-02-20T11:44:35+00:00
12,665
false
class Solution:\n # @return a list of lists of length 4, [[val1,val2,val3,val4]]\n def fourSum(self, num, target):\n two_sum = collections.defaultdict(list)\n res = set()\n for (n1, i1), (n2, i2) in itertools.combinations(enumerate(num), 2):\n two_sum[i1+i2].append({n1, n2})\n for t in list(two_sum.keys()):\n if not two_sum[target-t]:\n continue\n for pair1 in two_sum[t]:\n for pair2 in two_sum[target-t]:\n if pair1.isdisjoint(pair2):\n res.add(tuple(sorted(num[i] for i in pair1 | pair2)))\n del two_sum[t]\n return [list(r) for r in res]
28
0
['Python']
7
4sum
C++ Simple and Clean O(n^2) Solution, Including detailed explanation
c-simple-and-clean-on2-solution-includin-vc39
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 chec
yehudisk
NORMAL
2021-07-16T12:00:02.837424+00:00
2021-07-16T12:00:22.076654+00:00
3,833
false
**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!**
26
2
['C']
5
4sum
Optimized C++ solution, beats 99.8%
optimized-c-solution-beats-998-by-adyd-8qq5
cpp\nvector<vector<int>> fourSum(vector<int>& nums, int target) {\n\tstd::vector<std::vector<int>> result;\n\tstd::size_t n = nums.size();\n\tif (n < 4) {\n\t\t
adyd
NORMAL
2019-08-29T10:54:46.070915+00:00
2019-08-29T11:00:06.765688+00:00
5,057
false
```cpp\nvector<vector<int>> fourSum(vector<int>& nums, int target) {\n\tstd::vector<std::vector<int>> result;\n\tstd::size_t n = nums.size();\n\tif (n < 4) {\n\t\treturn result;\n\t}\n\n\tstd::sort(nums.begin(), nums.end());\n\tfor (int i = 0; i < n-3; ++i) {\n\t\t/* Conditions for pruning */\n\t\t// target too small, no point in continuing\n\t\tif (target <= 0 and nums[i] > 0) break;\n\t\t// nums[i] has become too large, no point in continuing\n\t\tif (nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break;\n\t\t// nums[i] is so small, even the largest elements cannot help reach the sum\n\t\tif (nums[i] + nums[n-3] + nums[n-2] + nums[n-1] < target) continue; \n\t\t // skip duplicates\n\t\tif (i > 0 and nums[i] == nums[i-1]) continue;\n\n\t\t/* Now explore further */\n\t\tfor (int j = i+1; j < n - 2; ++j) {\n\t\t\t/* Some more pruning */\n\t\t\t// nums[j] has become too large, no point in continuing\n\t\t\tif (nums[i] + nums[j] + nums[j+1] + nums[j+2] > target) break;\n\t\t\t// nums[j] is so small, even the largest elements cannot help reach the sum\n\t\t\tif (nums[i] + nums[j] + nums[n-2] + nums[n-1] < target) continue; \n\t\t\tif (j > i+1 and nums[j] == nums[j-1]) continue; // skip duplicates\n\n\t\t\t/* Explore the solution space */\n\t\t\tint left = j+1, right = n-1;\n\t\t\twhile (left < right) {\n\t\t\t\tint sum = nums[i] + nums[j] + nums[left] + nums[right];\n\t\t\t\tif (sum == target) {\n\t\t\t\t\tresult.push_back({nums[i], nums[j], nums[left], nums[right]});\n\t\t\t\t\tint last_left = nums[left], last_right = nums[right];\n\t\t\t\t\twhile (left < right and nums[left] == last_left) ++left;\n\t\t\t\t\twhile (left < right and nums[right] == last_right) --right;\n\t\t\t\t} else if (sum < target) {\n\t\t\t\t\t++left;\n\t\t\t\t} else {\n\t\t\t\t\t--right;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n```
25
3
['Two Pointers', 'C', 'Sorting', 'C++']
6
4sum
Easiest approach exists on earth 🤣🤣
easiest-approach-exists-on-earth-by-yada-aq2i
ApproachCheck Array Length: First, check if the length of the input array is less than 4. If yes, return an empty array or list because we can't form a valid gr
Yadav_Akash_
NORMAL
2025-01-22T18:44:26.306661+00:00
2025-01-23T16:46:44.261760+00:00
5,580
false
# Approach <!-- Describe your approach to solving the problem. --> Check Array Length: First, check if the length of the input array is less than 4. If yes, return an empty array or list because we can't form a valid group of 4 elements. Sort the Array: Sort the array in ascending order. Sorting helps us manage duplicates and makes it easier to work with combinations. Find Unique Combinations: Use a loop to go through the array and look for groups of 4 numbers. While looping, skip any duplicates by using an if condition to check if the current number is the same as the previous one. Store Results: For each valid group of 4 numbers without duplicates, add it to the result list. Return the Result: After completing the loops, return the list of unique combinations. # Complexity - Time complexity:O(n3) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(k) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> li=new ArrayList<>(); if(nums==null || nums.length<4){ return li; } Arrays.sort(nums); for(int i=0;i<nums.length-3;i++){ if(i>0&&nums[i]==nums[i-1]){ continue; } for(int j=i+1;j<nums.length-2;j++){ if(j>i+1&&nums[j]==nums[j-1]){ continue; } int left=j+1; int right=nums.length-1; while(left<right){ long sum=(long)nums[i]+nums[j]+nums[left]+nums[right]; if(sum==target){ li.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right])); while(left<right&&nums[left]==nums[left+1]){ left++; } while(left<right&&nums[right]==nums[right+-1]){ right--; } left++; right--; }else if(sum<target){ left++; }else{ right--; } } } } return li; } } ``` # IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION. ![one.png](https://assets.leetcode.com/users/images/52f058b1-7e1c-4460-85e5-0c939522264a_1737650788.05699.png)
24
0
['Java']
0
4sum
Short & Simple Solution in Python
short-simple-solution-in-python-by-yli24-sz1k
\n\tdef 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
yli249
NORMAL
2021-10-21T14:59:43.945318+00:00
2021-10-21T14:59:43.945352+00:00
3,582
false
\n\tdef 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):\n for j in range(i+1,n):\n left = j + 1\n right = n - 1\n\n while left < right:\n total = nums[i] + nums[left] + nums[right]+nums[j]\n if total > target:\n right -= 1\n elif total < target:\n left += 1\n else:\n ans.add(tuple(sorted((nums[i], nums[left], nums[right],nums[j]))))\n \n left += 1\n right -= 1\n return ans
22
0
['Two Pointers', 'Sorting', 'Ordered Set', 'Python', 'Python3']
7
4sum
Clean C++ 19ms backtracking 81.90%
clean-c-19ms-backtracking-8190-by-zefeng-hax8
\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n sort(nums.begin(), nums.end());\n vector<vector<in
zefengsong
NORMAL
2017-09-01T04:44:05.021000+00:00
2017-09-01T04:44:05.021000+00:00
2,394
false
```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n sort(nums.begin(), nums.end());\n vector<vector<int>>res;\n vector<int>path;\n DFS(res, nums, 0, target, 0, 0, path);\n return res;\n }\n \n void DFS(vector<vector<int>>& res, vector<int>& nums, int pos, int target, int count, int sum, vector<int>& path){\n if(count == 4){\n if(sum == target) res.push_back(path);\n return;\n }\n for(int i = pos; i < nums.size(); i++){\n if(i != pos && nums[i] == nums[i - 1]) continue;\n if(sum + nums[i] + (3 - count) * nums[nums.size() - 1] < target) continue;\n if(sum + (4 - count)* nums[i] > target) break;\n path.push_back(nums[i]);\n DFS(res, nums, i + 1, target, count + 1, sum + nums[i], path);\n path.pop_back();\n }\n }\n};\n```
20
1
['Backtracking', 'C++']
5
4sum
UNIVERSAL Solution To Solve Any N-Sum Problem Using Recursion
universal-solution-to-solve-any-n-sum-pr-5odr
javascript\nvar fourSum = function(nums, target) {\n nums.sort((a, b) => a - b);\n const result = [];\n \n // k represents N-sum, \n // if k = 3
control_the_narrative
NORMAL
2020-06-06T07:13:57.824621+00:00
2020-06-06T07:13:57.824652+00:00
2,254
false
```javascript\nvar fourSum = function(nums, target) {\n nums.sort((a, b) => a - b);\n const result = [];\n \n // k represents N-sum, \n // if k = 3 : 3Sum, if k = 4 : 4Sum, if k = 5, 5Sum; \n function recurse(arr, tar, res, k) {\n if(k === 2) {\n twoSum(arr, tar, res);\n return;\n }\n \n for(let i = 0; i < arr.length; i++) {\n while(arr[i] === arr[i-1]) i++;\n recurse(arr.slice(i+1), tar - arr[i], [...res, arr[i]], k-1);\n }\n }\n \n function twoSum(arr, tar, res) {\n let low = 0, high = arr.length-1;\n \n while(low < high) {\n const sum = arr[low] + arr[high];\n if(sum === tar) {\n result.push([...res, arr[low], arr[high]]);\n while(arr[low] === arr[low+1]) low++;\n while(arr[high] === arr[high-1]) high--;\n low++;\n high--;\n } else if(sum < tar) low++;\n else high--;\n }\n }\n \n recurse(nums, target, [], 4)\n return result\n};\n```
19
0
['JavaScript']
2
4sum
A conise python solution based on ksum
a-conise-python-solution-based-on-ksum-b-gkd4
class Solution:\n # @return a list of lists of length 4, [[val1,val2,val3,val4]]\n def fourSum(self, num, target):\n num.sort()\n
hucao1
NORMAL
2015-03-21T20:13:28+00:00
2015-03-21T20:13:28+00:00
4,555
false
class Solution:\n # @return a list of lists of length 4, [[val1,val2,val3,val4]]\n def fourSum(self, num, target):\n num.sort()\n def ksum(num, k, target):\n i = 0\n result = set()\n if k == 2:\n j = len(num) - 1\n while i < j:\n if num[i] + num[j] == target:\n result.add((num[i], num[j]))\n i += 1\n elif num[i] + num[j] > target:\n j -= 1\n else:\n i += 1\n else:\n while i < len(num) - k + 1:\n newtarget = target - num[i]\n subresult = ksum(num[i+1:], k - 1, newtarget)\n if subresult:\n result = result | set( (num[i],) + nr for nr in subresult)\n i += 1\n \n return result\n \n return [list(t) for t in ksum(num, 4, target)]
19
0
[]
1
4sum
[0ms][100%][Fastest Solution Explained] O(n) time complexity | O(n) space complexity
0ms100fastest-solution-explained-on-time-y0u7
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\nTake care brother, pe
darian-catalin-cucer
NORMAL
2022-05-20T14:39:05.048901+00:00
2022-06-27T08:11:59.237246+00:00
4,587
false
(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***Take care brother, peace, love!***\n\n```\n```\n\nThe best result for the code below is ***0ms / 38.2MB*** (beats 92.04% / 24.00%).\n* *** Kotlin ***\n\n```\n\nclass Solution {\n fun fourSum(nums: IntArray, target: Int): List<List<Int>> {\n\tval arrayList = ArrayList<List<Int>>()\n\tnums.sort() // sort necessary to filter out duplicates\n\n\tfor (i in 0 until nums.size) {\n\t\tif (i > 0 && nums[i] == nums[i - 1]) {\n\t\t\tcontinue //since sorted, it is ok to skip and remove duplicates.\n\t\t}\n\n\t\tfor (j in i + 1 until nums.size) {\n\t\t\tif (j > i + 1 && nums[j] == nums[j - 1]) {\n\t\t\t\tcontinue //since sorted, it is ok to skip and remove duplicates.\n\t\t\t}\n\n\t\t\tval friend = target - nums[i] - nums[j]\n\t\t\tvar left = j + 1\n\t\t\tvar right = nums.size - 1\n\n\t\t\twhile (left < right) {\n\t\t\t\tval sumIJ = nums[left] + nums[right]\n\t\t\t\twhen {\n\t\t\t\t\tsumIJ < friend -> left++\n\t\t\t\t\tsumIJ > friend -> right--\n\t\t\t\t\tsumIJ == friend -> {\n\t\t\t\t\t\t//detect duplicates, since they are in order, duplicates will be adjacent.\n\t\t\t\t\t\t//so it is sufficient to compare to previous value\n\t\t\t\t\t\tif (left > j + 1 && right < nums.size - 1) {\n\t\t\t\t\t\t\tif (nums[left] != nums[left - 1] || nums[right] != nums[right + 1]) {\n\t\t\t\t\t\t\t\tarrayList.add(listOf(nums[i], nums[j], nums[left], nums[right]))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tarrayList.add(listOf(nums[i], nums[j], nums[left], nums[right]))\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tleft++\n\t\t\t\t\t\tright--\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn arrayList\n}\n}\n\n```\n\n```\n```\n\n```\n```\n***"We are Anonymous. We are legion. We do not forgive. We do not forget. Expect us. Open your eyes.." - \uD835\uDCD0\uD835\uDCF7\uD835\uDCF8\uD835\uDCF7\uD835\uDD02\uD835\uDCF6\uD835\uDCF8\uD835\uDCFE\uD835\uDCFC***
18
2
['C', 'Java', 'Kotlin', 'JavaScript']
6
4sum
✅Easy C++ solution with explanation using 4 pointers!
easy-c-solution-with-explanation-using-4-lwpg
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!\u27
dhruba-datta
NORMAL
2021-10-28T14:59:49.933757+00:00
2022-04-14T19:56:08.346342+00:00
1,695
false
> **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>
18
0
['C', 'C++']
4
4sum
Python 76 ms beats 97.09%, explain why it is fast.
python-76-ms-beats-9709-explain-why-it-i-eocx
Problem:\n\n> Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all uniq
jerry_xiazj
NORMAL
2019-12-13T09:51:03.806466+00:00
2019-12-13T09:58:22.438334+00:00
5,164
false
# Problem:\n\n> Given an array `nums` of *n* integers and an integer `target`, are there elements *a*, *b*, *c*, and *d* in `nums` such that *a* + *b* + *c* + *d* = `target`? Find all unique quadruplets in the array which gives the sum of `target`. The solution set must not contain duplicate quadruplets.\n\nExample :\n\n\n```\nGiven array nums = [1, 0, -1, 0, -2, 2], and target = 0.\n\nA solution set is:\n[\n [-1, 0, 0, 1],\n [-2, -1, 1, 2],\n [-2, 0, 0, 2]\n]\n```\n\n## Solution 1\n\n```python\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n nums.sort()\n i = 0\n L = len(nums)\n res = []\n while i < L-3:\n j = i+1\n while j < L-2:\n left = j+1\n right = L-1\n new_target = target-nums[i]-nums[j]\n while left<right:\n if nums[left]+nums[right] > new_target:\n right-=1\n elif nums[left]+nums[right] < new_target:\n left+=1\n else:\n res.append([nums[i],nums[j],nums[left],nums[right]])\n temp_left = nums[left]\n temp_right = nums[right]\n while(left<right and nums[left]==temp_left):\n left+=1\n while(left<right and nums[right]==temp_right):\n right-=1\n while j < L-3 and nums[j] == nums[j+1]:\n j+=1\n j+=1\n while i < L-4 and nums[i] == nums[i+1]:\n i+=1\n i+=1\n return res\n```\n> Runtime: 880 ms; Memory Usage: 12.8 MB\n\n## Solution 2\n\n```python\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n nums.sort()\n res = []\n self.findNSum(nums, target, 4, [], res)\n return res\n\n def findNSum(self, nums, target, N, prefix, result):\n L = len(nums)\n if N == 2:\n l, r = 0, L-1\n while l < r:\n add = nums[l] + nums[r]\n if add == target:\n result.append(prefix + [nums[l], nums[r]])\n l += 1\n r -= 1\n while l<r and nums[l-1] == nums[l]:\n l += 1\n while l<r and nums[r+1] == nums[r]:\n r -= 1\n elif add > target:\n r -= 1\n else:\n l += 1\n else:\n for i in range(L-N+1):\n if target < N*nums[i] or target > N*nums[-1]: # key judgement\n break\n if i == 0 or (i>0 and nums[i] != nums[i-1]):\n self.findNSum(nums[i+1:], target-nums[i], N-1, prefix+[nums[i]], result)\n return\n```\n> Runtime: 84 ms; Memory Usage: 12.8 MB\n\n## Solution 3\n\n```python\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n nums.sort()\n i = 0\n L = len(nums)\n res = []\n while i < L-3:\n if target-nums[i] < 3*nums[i+1] or target-nums[i] > 3*nums[-1]:\n while i < L-4 and nums[i] == nums[i+1]:\n i+=1\n i+=1\n continue\n j = i+1\n while j < L-2:\n if target-nums[i]-nums[j] < 2*nums[j+1] or target-nums[i]-nums[j] > 2*nums[-1]:\n while j < L-3 and nums[j] == nums[j+1]:\n j+=1\n j+=1\n continue\n left = j+1\n right = L-1\n new_target = target-nums[i]-nums[j]\n while left<right:\n if nums[left]+nums[right] > new_target:\n right-=1\n elif nums[left]+nums[right] < new_target:\n left+=1\n else:\n res.append([nums[i],nums[j],nums[left],nums[right]])\n temp_left = nums[left]\n temp_right = nums[right]\n while(left<right and nums[left]==temp_left):\n left+=1\n while(left<right and nums[right]==temp_right):\n right-=1\n while j < L-3 and nums[j] == nums[j+1]:\n j+=1\n j+=1\n while i < L-4 and nums[i] == nums[i+1]:\n i+=1\n i+=1\n return res\n```\n> Runtime: 76 ms; Memory Usage: 12.8 MB\n\n## Note:\n\n- \u5728\u7B2C\u4E8C\u79CD\u7B97\u6CD5\u662F\u9012\u5F52\u7B97\u6CD5\u3002\n- \u7B2C\u4E8C\u79CD\u7B97\u6CD5\u6BD4\u7B2C\u4E00\u79CD\u7B97\u6CD5\u5FEB\u5728`line 28`\uFF0C\u5373\u5173\u952E\u5224\u65AD\u3002\n- \u7B2C\u4E09\u79CD\u7B97\u6CD5\u662F\u5728\u7B2C\u4E00\u79CD\u7B97\u6CD5\u7684\u57FA\u7840\u4E0A\u589E\u52A0\u4E86\u5173\u952E\u5224\u65AD\uFF0C\u901F\u5EA6\u5F97\u5230\u5927\u5E45\u63D0\u5347\u3002\u5E76\u4E14\u6BD4\u9012\u5F52\u7B97\u6CD5\u66F4\u5FEB\u3002\n- Solution 2 is recursive algorithm.\n- Solution 2 is faster than solution 1 because of `line 28`, which is the key judgement.\n- Adding the key judgement to solution1 makes solution 3, which is even faster than recursive algorithm solution 2.
18
0
['Python', 'Python3']
2
4sum
Share my python code, run time 200+- 20ms
share-my-python-code-run-time-200-20ms-b-obuz
class Solution:\n # @return a list of lists of length 4, [[val1,val2,val3,val4]]\n def fourSum(self, num, target):\n num.sort()\n
lightmanliu
NORMAL
2015-03-30T03:30:21+00:00
2018-09-29T11:26:46.758985+00:00
6,208
false
class Solution:\n # @return a list of lists of length 4, [[val1,val2,val3,val4]]\n def fourSum(self, num, target):\n num.sort()\n result = []\n for i in xrange(len(num)-3):\n if num[i] > target/4.0:\n break\n if i > 0 and num[i] == num[i-1]:\n continue\n target2 = target - num[i]\n for j in xrange(i+1, len(num)-2):\n if num[j] > target2/3.0:\n break\n if j > i+1 and num[j] == num[j-1]:\n continue\n k = j + 1\n l = len(num) - 1\n target3 = target2 - num[j]\n # we should use continue not break\n # because target3 changes as j changes\n if num[k] > target3/2.0:\n continue\n if num[l] < target3/2.0:\n continue\n while k < l:\n sum_value = num[k] + num[l]\n if sum_value == target3:\n result.append([num[i], num[j], num[k], num[l]])\n kk = num[k]\n k += 1\n while k<l and num[k] == kk:\n k += 1\n \n ll = num[l]\n l -= 1\n while k<l and num[l] == ll:\n l -= 1\n elif sum_value < target3:\n k += 1\n else:\n l -= 1\n return result\n\nWe can reduce run time by adding some restrictions.
18
0
['Python']
6
4sum
Clear and simple python3 solution with comment (O(n^3))
clear-and-simple-python3-solution-with-c-xxtv
python\nclass Solution:\n def fourSum(self, nums, target: int):\n res = []\n nums.sort()\n\n # loop for first num, n times\n for
littlebeandog
NORMAL
2019-03-22T11:17:56.217005+00:00
2019-03-22T11:17:56.217048+00:00
1,612
false
```python\nclass Solution:\n def fourSum(self, nums, target: int):\n res = []\n nums.sort()\n\n # loop for first num, n times\n for i in range(len(nums) - 3):\n \n # skip duplication\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n\n # skip uneccesary case\n if nums[i] * 4 > target:\n break\n\n # loop for second number, n times\n for j in range(i + 1, len(nums) - 2):\n \n # skip duplication\n if j > i + 1 and nums[j] == nums[j - 1]:\n continue\n\n # skip uneccesary case\n if nums[j] * 3 > target - nums[i]:\n break\n\n # search for last 2 nums, same as 2Sum/3Sum problem\n l, r = j + 1, len(nums) - 1\n\n while l < r:\n \n s = nums[i] + nums[j] + nums[l] + nums[r]\n if s > target:\n r = r - 1\n elif s < target:\n l = l + 1\n else:\n res.append([nums[i], nums[j], nums[l], nums[r]])\n while l < r and nums[l] == nums[l + 1]:\n l = l + 1\n while l < r and nums[r] == nums[r - 1]:\n r = r - 1\n l, r = l + 1, r - 1\n \n return res\n\t\t```
17
1
['Python']
4
4sum
C++/Java/Python/JavaScript || 🚀 ✅ Two Pointer || 🚀 ✅Array
cjavapythonjavascript-two-pointer-array-c8r4s
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
devanshupatel
NORMAL
2023-05-11T14:07:20.403912+00:00
2023-05-11T14:07:20.403950+00:00
9,401
false
# 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: [https://leetcode.com/problems/3sum/solutions/3416585/c-java-python-javascript-fully-explained-two-pointer-array/?orderBy=most_votes]()\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: [https://leetcode.com/problems/3sum/solutions/3416585/c-java-python-javascript-fully-explained-two-pointer-array/?orderBy=most_votes]()
16
0
['Two Pointers', 'Python', 'C++', 'Java', 'JavaScript']
1
4sum
Java backtracking solution for K-sum beat 94%
java-backtracking-solution-for-k-sum-bea-q46p
Some tips:\n1) avoid sum cases by viewing nums[start]k and nums[end]k \n2) when backtracking, first add nums[i] to current list, after that then remove\n\nOne C
legolasgreenleaf
NORMAL
2016-01-04T10:41:00+00:00
2016-01-04T10:41:00+00:00
6,802
false
Some tips:\n1) avoid sum cases by viewing nums[start]*k and nums[end]*k \n2) when backtracking, first add nums[i] to current list, after that then remove\n\nOne C++ Reference: http://bangbingsyb.blogspot.hk/2014/11/leetcode-4sum.html \n\n public class Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n Arrays.sort(nums);\n kSum(result, new ArrayList<Integer>(), nums, target, 4, 0, nums.length-1);\n return result;\n }\n \n private void kSum(List<List<Integer>> result,List<Integer> cur,int[] nums, int target,int k,int start, int end){\n if(k == 0 || nums.length==0 || start>end) return;\n if(k == 1){\n for (int i = start; i <= end ; i++) {\n if(nums[i] == target){\n cur.add(nums[i]);\n result.add(new ArrayList<Integer>(cur));\n cur.remove(cur.size()-1);\n }\n }\n return;\n }\n \n if(k == 2){ // 2 sum\n int sum;\n while (start < end){\n sum = nums[start]+nums[end];\n \n if(sum == target){\n cur.add(nums[start]);\n cur.add(nums[end]);\n result.add(new ArrayList<Integer>(cur));\n cur.remove(cur.size()-1);\n cur.remove(cur.size()-1);\n \n //avoid duplicate\n while(start < end && nums[start] == nums[start+1]) ++start;\n ++start;\n while(start < end && nums[end] == nums[end-1]) --end;\n --end;\n }else if(sum < target){\n //avoid duplicate\n while(start < end && nums[start] == nums[start+1]) ++start;\n ++start;\n }else{\n while(start < end && nums[end] == nums[end-1]) --end;\n --end;\n }\n }\n return;\n }\n \n //\u907f\u514d\u4e00\u4e9b\u4e0d\u5fc5\u8981case\n if(k*nums[start] > target || k*nums[end]<target) return;\n \n // k > 2 : choose nums[i] and do k-1 sum on the rest at right\n for (int i = start; i <= (end-k+1) ; i++) {\n // avoid duplicate\n if(i>start && nums[i]==nums[i-1]) continue;\n // \u91cd\u70b9\n if(k*nums[i] <= target) { //\u907f\u514d\u6389\u4e00\u4e9b\u4e0d\u5fc5\u8981case\n cur.add(nums[i]);\n kSum(result, cur, nums, target - nums[i], k - 1, i + 1, end);\n cur.remove(cur.size() - 1);\n }\n }\n \n }\n }
16
0
['Backtracking']
5
4sum
Brute to Optimal || Beginner-Friendly Solution || Easy Video Explanation in Hindi
brute-to-optimal-beginner-friendly-solut-8we8
Ek Video me Saara Funda Clear (Easy Explanation in Hindi)\n\n## Click Here : www.youtube.com/watch?v=RblHmfT8JLI&list=PL4JcMBI4LmknXBJsifFkvdrOix7ukBsHC&index=8
nayankumarjha2
NORMAL
2024-03-14T12:13:48.336913+00:00
2024-03-14T12:13:48.336949+00:00
4,256
false
## Ek Video me Saara Funda Clear (Easy Explanation in Hindi)\n\n## Click Here : www.youtube.com/watch?v=RblHmfT8JLI&list=PL4JcMBI4LmknXBJsifFkvdrOix7ukBsHC&index=8\n\n# Complexity\n- Time complexity: $$O(N^3)$$\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# C++\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size();\n\n vector<vector<int>> ans;\n sort(nums.begin(), nums.end());\n\n set<vector<int>> uniqueSets;\n\n for(int i = 0; i < n; i++){\n for(int j = i + 1; j < n; j++){\n int k = j + 1;\n int l = n - 1;\n\n while(k < l){\n long long sum = static_cast<long long>(nums[i]) + nums[j] + nums[k] + nums[l];\n\n if(sum == target){\n vector<int> quadruplet = {nums[i], nums[j], nums[k], nums[l]};\n uniqueSets.insert(quadruplet);\n k++;\n l--;\n }\n else if(sum < target) k++;\n else if(sum > target) l--;\n }\n }\n }\n \n ans.assign(uniqueSets.begin(), uniqueSets.end());\n return ans;\n }\n};\n```\n# Java\n```\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n int n = nums.length;\n\n List<List<Integer>> ans = new ArrayList<>();\n Arrays.sort(nums);\n\n Set<List<Integer>> set = new HashSet<>();\n\n for(int i=0; i<n; i++){\n for(int j=i+1; j<n; j++){\n int k = j+1;\n int l = n-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> al = new ArrayList<>();\n al.add(nums[i]);\n al.add(nums[j]);\n al.add(nums[k]);\n al.add(nums[l]);\n\n set.add(al);\n k++;\n l--;\n }\n\n else if(sum < target) k++;\n else if(sum > target) l--;\n \n }\n }\n }\n \n ans.addAll(set);\n return ans;\n }\n}\n```\n# Python3\n```\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n n = len(nums)\n nums.sort()\n\n ans = []\n unique_set = set()\n\n for i in range(n):\n for j in range(i + 1, n):\n k = j + 1\n l = n - 1\n\n while k < l:\n total_sum = nums[i] + nums[j] + nums[k] + nums[l]\n\n if total_sum == target:\n temp = [nums[i], nums[j], nums[k], nums[l]]\n unique_set.add(tuple(temp))\n k += 1\n l -= 1\n elif total_sum < target:\n k += 1\n elif total_sum > target:\n l -= 1\n\n ans = list(unique_set)\n return ans\n```\n## Please Upvote if you liked the Solution.
15
0
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'C++', 'Java', 'Python3']
2
4sum
✅ EASIEST || 💯 BEATS || 🧑‍💻 JAVA || ⭐ TWO POINTERS
easiest-beats-java-two-pointers-by-mukun-7ls6
\n\n# \u2B50 Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem builds on the "two-sum" and "three-sum" problems. To find fou
mukund_rakholiya
NORMAL
2024-10-25T09:28:00.465531+00:00
2024-10-25T09:28:00.465568+00:00
5,948
false
```\n```\n# \u2B50 Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**This problem builds on the "two-sum" and "three-sum" problems. To find four numbers that add up to a target value, we can try a sorted array and use two nested loops for the first two numbers. For the remaining pair, we can apply a two-pointer approach to find all unique quadruplets.**\n\n```\n```\n# \u2B50 Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Sort the Array**: Sorting the array helps simplify handling duplicate values and allows the two-pointer technique.\n\n2. **Nested Loops**: Use two nested loops to pick the first two numbers, nums[i] and nums[j]. Ensure these loops skip duplicates to avoid redundant calculations.\n\n3. **Two-Pointer Search**: For the remaining two numbers, use two pointers (k starting right after j and l at the end of the array).\n - If the sum of nums[i], nums[j], nums[k], and nums[l] matches the target, add the quadruplet to the result.\n - Adjust pointers k and l to find other potential pairs, ensuring you skip over duplicates.\n\n4. **Result Storage**: Store each unique quadruplet in a list and return this list of lists.\n\n```\n```\n# \u2B50 Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**$$O(n3)$$ due to the nested loop structure and the two-pointer search for each unique pair.**\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**$$O(m)$$, where $$m$$ is the number of unique quadruplets stored in the result list.**\n```\n```\n# \u2B50 Code\n```java []\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>> ans = new ArrayList<>();\n int len = nums.length;\n\n Arrays.sort(nums);\n\n for (int i = 0; i < len - 3; i++) {\n if (i > 0 && nums[i - 1] == nums[i]) \n continue;\n\n for (int j = i + 1; j < len - 2; j++) {\n if (j > i + 1 && nums[j - 1] == nums[j])\n continue;\n \n int k = j + 1;\n int l = len - 1;\n\n while (k < l) {\n long sum = nums[i] + nums[j];\n sum += nums[k] + nums[l];\n\n if (sum == target) {\n ans.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));\n k++;\n l--;\n\n while (k < l && nums[k - 1] == nums[k]) k++;\n \n while (k < l && nums[l + 1] == nums[l]) l--;\n } else if (sum < target)\n k++;\n else \n l--;\n }\n }\n }\n\n return ans;\n }\n}\n```\n\n```\n```\n\n![upvote.png](https://assets.leetcode.com/users/images/78a73912-d1ac-4b9c-baa5-d95d17c9161d_1729847953.8020196.png)\n
14
0
['Array', 'Two Pointers', 'Sorting', 'Java']
5
4sum
Two-Pointers Solution || Java || O(N^3) time
two-pointers-solution-java-on3-time-by-b-hm0e
\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>>ans = new ArrayList<>();\n Arrays.sort(n
Bhawna05
NORMAL
2021-09-28T10:13:30.422997+00:00
2022-10-15T06:05:24.188715+00:00
2,358
false
```\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>>ans = new ArrayList<>();\n Arrays.sort(nums);\n for(int i=0; i<nums.length-3; i++) {\n if(i==0 || i>0 && nums[i]!=nums[i-1]) {\n for(int j=i+1; j<nums.length-2; j++) {\n if(j==i+1 || (j>i+1 && nums[j]!=nums[j-1])) {\n int low = j+1;\n int high = nums.length-1;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//to prevent integer overflow\n long sum = nums[i]+nums[j];\n long val = ((long)target - sum);\n\t\t\t\t\t\t\n while(low < high) {\n if(nums[low]+nums[high] < val)\n low++;\n else if(nums[low]+nums[high] > val)\n high--;\n else {\n ans.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high]));\n while(low<high && nums[low]==nums[low+1])\n low++;\n while(low<high && nums[high]==nums[high-1])\n high--;\n low++;\n high--;\n }\n }\n }\n }\n }\n }\n return ans;\n }\n}\n```
14
0
['Two Pointers', 'Java']
4
4sum
Generic K Sum | Easy to understand
generic-k-sum-easy-to-understand-by-nits-vydr
\n\ninterface IKSum {\n\n List<List<Integer>> kSum(int nums[], int k, int target);\n}\n\n/**\n * We\'ll use the problem of k sum and reduce it to two sum and
nits2010
NORMAL
2019-08-16T06:19:08.041097+00:00
2019-08-16T06:19:08.041131+00:00
6,710
false
```\n\ninterface IKSum {\n\n List<List<Integer>> kSum(int nums[], int k, int target);\n}\n\n/**\n * We\'ll use the problem of k sum and reduce it to two sum and attache the result back\n */\nclass KSumSorting implements IKSum {\n\n @Override\n public List<List<Integer>> kSum(int[] nums, int k, int target) {\n if (nums == null || nums.length == 0 || nums.length < k)\n return Collections.EMPTY_LIST;\n\n Arrays.sort(nums);\n\n return kSum(nums, k, 0, target);\n\n }\n\n private List<List<Integer>> kSum(int[] nums, int k, int start, int target) {\n int len = nums.length;\n List<List<Integer>> result = new ArrayList<>();\n if (len < k)\n return Collections.EMPTY_LIST;\n\n if (k == 2) {\n return twoSum(nums, start, len - 1, target);\n } else {\n\n /**\n * Take each element, and exclude it from target to reduce the problem to smaller k-1 sum problem\n */\n for (int i = start; i < len - (k - 1); i++) {\n /**\n * Avoid duplicates\n */\n if (i > start && nums[i] == nums[i - 1])\n continue;\n\n int ele = nums[i];\n\n int rem = target - nums[i];\n List<List<Integer>> smallerSumResult = kSum(nums, k - 1, i + 1, rem);\n\n /**\n * Append the current element to make it k sum from k-1 sum\n */\n for (List<Integer> list : smallerSumResult)\n list.add(0, ele);\n\n /**\n * Append to our result\n */\n result.addAll(smallerSumResult);\n\n\n }\n }\n\n return result;\n }\n\n private List<List<Integer>> twoSum(int nums[], int low, int high, int target) {\n\n List<List<Integer>> result = new ArrayList<>();\n\n while (low < high) {\n\n int sum = nums[low] + nums[high];\n\n if (sum == target) {\n List<Integer> twoSum = new ArrayList<>();\n twoSum.add(nums[low]);\n twoSum.add(nums[high]);\n\n result.add(twoSum);\n\n /**\n * Avoid duplicates\n */\n\n while (low < high && nums[low] == nums[++low]) ;\n while (high > low && nums[high] == nums[--high]) ;\n\n } else if (sum < target)\n low++;\n else\n high--;\n\n }\n\n return result;\n }\n}\n\n```\n\nDriver code\n\n```\n\npublic class KSum {\n public static void main(String[] args) {\n test(new int[]{1, 0, -1, 0, -2}, 4, 0);\n\n test(new int[]{1, 0, -1, 0, -2, 2}, 4, 0);\n\n test(new int[]{-3, -2, -1, 0, 0, 1, 2, 3}, 4, 0);\n\n test(new int[]{-4, -3, -2, -1, 0, 0, 1, 2, 3, 4}, 4, 0);\n\n\n test(new int[]{1, 0, -1, 0, -2}, 5, 0);\n\n test(new int[]{1, 0, -1, 0, -2, 2}, 5, 0);\n\n test(new int[]{-3, -2, -1, 0, 0, 1, 2, 3}, 5, 0);\n\n test(new int[]{-4, -3, -2, -1, 0, 0, 1, 2, 3, 4}, 5, 0);\n\n\n test(new int[]{1, 0, -1, 0, -2}, 3, 0);\n\n test(new int[]{1, 0, -1, 0, -2, 2}, 3, 0);\n\n test(new int[]{-3, -2, -1, 0, 0, 1, 2, 3}, 3, 0);\n\n test(new int[]{-4, -3, -2, -1, 0, 0, 1, 2, 3, 4}, 3, 0);\n\n\n\n test(new int[]{1, 0, -1, 0, -2}, 2, 0);\n\n test(new int[]{1, 0, -1, 0, -2, 2}, 2, 0);\n\n test(new int[]{-3, -2, -1, 0, 0, 1, 2, 3}, 2, 0);\n\n test(new int[]{-4, -3, -2, -1, 0, 0, 1, 2, 3, 4}, 2, 0);\n\n }\n\n private static void test(int[] nums, int k, int target) {\n IKSum kSum = new KSumSorting();\n\n System.out.println("\\nInput : " + Printer.toString(nums) + " K :" + k + " Target: " + target);\n System.out.println("Sorting: " + kSum.kSum(nums, k, target));\n }\n\n\n}\n```
14
0
[]
1
4sum
(Java) 25 lines of code, easy to understand answer that is O(n^2), based on two sum solution
java-25-lines-of-code-easy-to-understand-hyja
\n public List<List<Integer>> fourSum(int[] nums, int target) {\n //because res can be duplicated, we use set to deal with that\n //Set of a li
celticrocks
NORMAL
2019-04-11T03:11:04.900878+00:00
2019-04-11T03:11:04.900935+00:00
1,123
false
```\n public List<List<Integer>> fourSum(int[] nums, int target) {\n //because res can be duplicated, we use set to deal with that\n //Set of a list compare all the elements in the list defaultly, you don\'t need to override compare and hash function\n Set<List<Integer>> res = new HashSet<List<Integer>>();\n if(nums == null || nums.length < 4) {\n return new ArrayList<>(res);\n }\n int n = nums.length;\n Arrays.sort(nums);\n //key represents sum of first two nums, value is the list of indexes of those two nums\n //We dont need to worry about duplicate here, we deal with that in res set\n Map<Integer, List<int[]>> map = new HashMap<>();\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n int sum = nums[i] + nums[j];\n //check if current nums[i] and nums[j] can combine with previous first two nums to get a target value; \n\t\t\t\tif(map.containsKey(target - sum)) {\n List<int[]> indexes = map.get(target - sum);\n\t\t\t\t\tfor(int[] index : indexes) {\n // Here we already know that we can get 4 nums to get the target value, but we need those four nums comes in order\n\t\t\t\t\t\t//assume we have first two nums nums[k], nums[l], and current nums are nums[i], nums[j], by definition, k < l and i < j are certain. So we only need to make sure that l < i, then we can get k < l < i < j, and add it to result set \n\t\t\t\t\t\tif(index[1] < i) {\n //make a result\n List<Integer> candidate = Arrays.asList(nums[index[0]], nums[index[1]], nums[i], nums[j]);\n res.add(candidate);\n }\n }\n }\n List<int[]> temp = map.getOrDefault(sum, new ArrayList<>());\n temp.add(new int[]{i, j});\n map.put(sum, temp);\n }\n }\n //convert from Set<List> to List<List>\n return new ArrayList<>(res);\n }\n```
14
1
[]
5
4sum
Optimal Solution for 4Sum Problem Using Two-Pointer Technique and Early Exits
optimal-solution-for-4sum-problem-using-d0niu
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is an extension of the classic two-sum and three-sum problems. Since we\'re
k-m-abrar-ahsan
NORMAL
2024-09-23T06:56:11.834322+00:00
2024-10-14T08:02:45.050402+00:00
2,931
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is an extension of the classic two-sum and three-sum problems. Since we\'re looking for quadruplets, we can use a combination of sorting and the two-pointer technique to reduce the problem\'s complexity. Sorting helps in easily skipping duplicates and narrowing down the search space for potential quadruplets. By using two nested loops to fix the first two numbers, we can then apply the two-pointer technique to find the remaining two numbers that complete the quadruplet.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Sorting:** First, sort the array. Sorting helps to avoid duplicates and enables the use of the two-pointer technique for efficiently finding the remaining numbers.\n\n**2. Nested Loops:** Use two loops to fix the first two numbers (a and b). Then, for each pair, use two pointers (left and right) to find the remaining two numbers (c and d).\n\n**3. Two Pointers:** For the fixed pair a and b, use two pointers (left starting from b+1 and right starting from the end of the array). Adjust the pointers based on the sum of the four numbers:\n\n- If the sum equals the target, record the quadruplet and move both pointers inward.\n- If the sum is less than the target, increment the left pointer to increase the sum.\n- If the sum is greater than the target, decrement the right pointer to reduce the sum.\n\n**4. Avoiding Duplicates:** After finding a valid quadruplet, move both pointers (left and right) past any duplicate values to ensure unique results.\n\n **5. Early Exit:** Use early exit conditions to avoid unnecessary computations:\n\n- If the smallest possible sum with the current numbers is greater than the target, stop further processing.\n- If the largest possible sum with the current numbers is less than the target, skip to the next iteration.\n# Complexity\n### Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(n^3), where n is the number of elements in the array. Sorting the array takes \nO(nlogn), and for each pair of numbers, the two-pointer technique takes O(n). Since we are looping over the array for two fixed numbers and then using the two-pointer technique, the overall time complexity is O(n^3).\n### Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) if we exclude the space needed for the result storage. Sorting the array is done in-place, and we only use a constant amount of extra space for variables and pointers. However, the result storage could take O(k) space, where k is the number of quadruplets found.\n# Code\n```python3 []\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n nums.sort() # Sort the array first\n n = len(nums)\n result = []\n \n # Iterate over the first two numbers\n for i in range(n - 3):\n # Early exit if the smallest sum exceeds the target\n if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:\n break\n \n # Skip duplicates for the first number\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n \n # Early exit if the largest possible sum is less than the target\n if nums[i] + nums[n-1] + nums[n-2] + nums[n-3] < target:\n continue\n \n for j in range(i + 1, n - 2):\n # Skip duplicates for the second number\n if j > i + 1 and nums[j] == nums[j - 1]:\n continue\n \n # Early exit for the second number\n if nums[i] + nums[j] + nums[j+1] + nums[j+2] > target:\n break\n\n if nums[i] + nums[j] + nums[n-1] + nums[n-2] < target:\n continue\n \n # Now use two pointers for the remaining two numbers\n left, right = j + 1, n - 1\n while left < right:\n total = nums[i] + nums[j] + nums[left] + nums[right]\n \n if total == target:\n result.append([nums[i], nums[j], nums[left], nums[right]])\n left += 1\n right -= 1\n \n # Skip duplicates for the third number\n while left < right and nums[left] == nums[left - 1]:\n left += 1\n \n # Skip duplicates for the fourth number\n while left < right and nums[right] == nums[right + 1]:\n right -= 1\n \n elif total < target:\n left += 1\n else:\n right -= 1\n \n return result\n```
13
0
['Array', 'Two Pointers', 'Dynamic Programming', 'Sorting', 'Python3']
2
4sum
💥 C# | Runtime and memory beats 95.29%
c-runtime-and-memory-beats-9529-by-r9n-n2jo
Intuition\nI have to find all unique sets of four numbers that sum up to a given target. To do this efficiently, I need to avoid checking the same set multiple
r9n
NORMAL
2024-09-10T21:53:20.053771+00:00
2024-09-10T21:53:20.053808+00:00
979
false
# Intuition\nI have to find all unique sets of four numbers that sum up to a given target. To do this efficiently, I need to avoid checking the same set multiple times and handle duplicates properly.\n\n# Approach\nSort the Array: Helps in managing duplicates and using the two-pointer technique.\n\nFix Two Numbers: Use two nested loops to choose the first two numbers.\n\nTwo-pointer Technique: Use pointers to find the other two numbers that make the target sum.\n\nSkip Duplicates: Ensure unique quadruplets by skipping duplicate values.\n\n# Complexity\n- Time complexity:\nO(n3) due to sorting and nested loops.\n\n- Space complexity:\nO(1) extra space (excluding result storage).\n\n# Code\n```csharp []\npublic class Solution\n{\n public IList<IList<int>> FourSum(int[] nums, int target)\n {\n Array.Sort(nums);\n var result = new List<IList<int>>();\n int n = nums.Length;\n\n for (int i = 0; i < n - 3; i++)\n {\n if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip duplicates for i\n\n for (int j = i + 1; j < n - 2; j++)\n {\n if (j > i + 1 && nums[j] == nums[j - 1]) continue; // Skip duplicates for j\n\n int left = j + 1;\n int right = n - 1;\n long targetSum = (long)target - nums[i] - nums[j]; // Use long to avoid overflow\n\n while (left < right)\n {\n long sum = (long)nums[left] + nums[right]; // Use long to avoid overflow\n if (sum == targetSum)\n {\n result.Add(new List<int> { nums[i], nums[j], nums[left], nums[right] });\n while (left < right && nums[left] == nums[left + 1]) left++; // Skip duplicates for left\n while (left < right && nums[right] == nums[right - 1]) right--; // Skip duplicates for right\n left++;\n right--;\n }\n else if (sum < targetSum) left++;\n else right--;\n }\n }\n }\n\n return result;\n }\n}\n\n```
13
0
['C#']
1
4sum
✅Accepted| | ✅Easy solution || ✅Short & Simple || ✅Best Method
accepted-easy-solution-short-simple-best-5bd8
\n# Code\n\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, long target) {\n vector<vector<int>> ans;\n sort(nums.be
sanjaydwk8
NORMAL
2023-01-14T06:22:04.701253+00:00
2023-01-14T06:22:04.701286+00:00
2,460
false
\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!!
13
0
['C++']
0
4sum
4SUM
4sum-by-gaddarkumar7447-8c92
class Solution {\n\n public List> fourSum(int[] nums, int target) {\n Arrays.sort(nums);\n Set> set = new HashSet<>();\n for(int i = 0;
gaddarkumar7447
NORMAL
2022-03-28T04:20:09.471322+00:00
2022-05-03T12:16:09.561964+00:00
1,017
false
class Solution {\n\n public List<List<Integer>> fourSum(int[] nums, int target) {\n Arrays.sort(nums);\n Set<List<Integer>> set = new HashSet<>();\n for(int i = 0; i < nums.length; i++){\n for(int j = i+1; j < nums.length; j++){\n int start = j+1;\n int end = nums.length-1;\n while(end > start){\n int sum = nums[i]+ nums[j] + nums[start] + nums[end];\n if(sum == target){\n set.add(Arrays.asList(nums[i], nums[j], nums[start++], nums[end--]));\n }\n else if (sum > target) end --;\n else start++;\n }\n }\n }\n return new ArrayList<>(set);\t\n }\n}\n\n**If you like to understand the solution than please Upvote me**
13
2
['Two Pointers', 'Java']
4
4sum
[C++] Recursion | 4ms, 99.81% faster | Code explained clearly
c-recursion-4ms-9981-faster-code-explain-1475
Here I used a very clever technique of reducing any n sum problem to a two sum by using recursing and simplification. The most time saving techniques was the sk
coolchirutha
NORMAL
2021-07-16T20:19:59.897229+00:00
2021-07-16T20:19:59.897261+00:00
1,097
false
Here I used a very clever technique of reducing any n sum problem to a two sum by using recursing and simplification. The most time saving techniques was the skipping of duplicates and unnecessry cases by using if cases. Read the code carefully and please do **upvote** if you like the approach.\n```\n/*\n READ THE CODE USING MY MARKERS OF 1 to 10. START WITH THE foursum method AND\n THEN READ nSum method AND FINALLY TO twoSum.\n*/\nclass Solution {\npublic:\n vector<vector<int>> twoSum(vector<int> &nums, int target, int start) {\n vector<vector<int>> result;\n // 7. Now we iterate through the array taking the two pointer approach and\n // try to find two values in the array to add to the result.\n int left = start, right = nums.size() - 1;\n while (left < right) {\n int curSum = nums[left] + nums[right];\n // 8. Now we need to move left pointer forward when sum is less than\n // target and also to avoid duplicates we do not consider the case when\n // nums[left] == nums[left - 1]. Here we write left > start to not check\n // nums[left] == nums[left - 1] when left == start.\n if (curSum < target || (left > start && nums[left] == nums[left - 1])) {\n left++;\n } else if (curSum > target || (right < nums.size() - 1 && nums[right] == nums[right + 1])) {\n // 9. Now we bring right pointer backwards when we have overshot the\n // target or when duplicates are recorded(nums[right] == nums[right + 1]\n // is to check for duplicates).\n right--;\n } else {\n // 10. This is executed when curSum == target.\n result.push_back({nums[left++], nums[right--]});\n }\n }\n return result;\n }\n\n vector<vector<int>> nSum(vector<int> &nums, int target, int start, int n) {\n vector<vector<int>> result;\n // 2. If the current start value has reached end or start element times n is\n // greater than target or target is smaller than last element times n. We\n // cannot get any solution.\n if (start == nums.size() || nums[start] * n > target ||\n target > nums.back() * n) {\n return result;\n }\n\n if (n == 2) {\n // 3. We simply calculate twoSum when we need to.\n return twoSum(nums, target, start);\n }\n\n // 4. When n > 2, we need to reduce the problem into a twosum problem. This\n // is done by taking a sub problem. Here we consider the ith element and\n // call the function itself to calculate sum for (n - 1)th sum with a new\n // target of (target - nums[i]). Also we should start the call for search\n // with a start index if i + 1 so as to avoid duplicates. We also consider\n // skipping nums[i] when nums[i - 1] == nums[i] because the array is sorted\n // and we will avoid duplicates to be detected.\n for (int i = start; i < nums.size(); i++) {\n if (i == start || nums[i - 1] != nums[i]) {\n for (auto &j : nSum(nums, target - nums[i], i + 1, n - 1)) {\n // 5. Now the j variable is an iterator to the vectors where a target\n // of (target - nums[i]) has been achieved and we use this iterator to\n // add to the vector inside the result where nums[i] is present.\n result.push_back({nums[i]});\n // 6. Here, since we just added nums[i] to result, we now insert\n // inside the vector of {nums[i]} the values which came from the n-1\n // sum call. These results are concatenated to the nums[i].\n result.back().insert(end(result.back()), begin(j), end(j));\n }\n }\n }\n return result;\n }\n\n vector<vector<int>> fourSum(vector<int> &nums, int target) {\n // 1. We need a sorted array\n sort(begin(nums), end(nums));\n return nSum(nums, target, 0, 4);\n }\n};\n```
13
0
['Recursion', 'C']
3
4sum
Solution in Python 3 (beats 100.00%) (48 ms) ( O(n³) ) (Asymptotic Analysis)
solution-in-python-3-beats-10000-48-ms-o-xaqx
Asymptotic Worst Case Analysis:\nFor ease of analysis, we will assume that the input list is sorted since sorting only takes O(n log n) time. The worst case occ
junaidmansuri
NORMAL
2019-08-31T21:04:20.159260+00:00
2019-12-30T06:35:39.478630+00:00
3,615
false
_Asymptotic Worst Case Analysis:_\nFor ease of analysis, we will assume that the input list is sorted since sorting only takes O(n log n) time. The worst case occurs if the target is equal to the sum of the four greatest elements in the list. This is because the search would have to continue until the very end to find the desired quadruplet _(a,b,c,d)_. For example, a list of the form _N_ = [1,2,3,4,5,6,7,8,9,10] with _target_ = 34 would require a complete run through all iterations of the three nested for loops. Note that the reason that there are only three nested for loops even though we are looking for a quadruplet is because finding the triplet _(a,b,c)_ determines a unique value of _d_ which will lead to a sum of _target_. Thus, we only need to search for triplets _(a,b,c)_ such that _target - (a+b+c)_ is in the original list.\n\nObserve that in the worst case, there is only one valid solution and that is found by adding the last four (i.e. the largest four) elements of the input list. Specifically, the desired quadruplet will be _( N[n-4], N[n-3], N[n-2], N[n-1] )_, where _N_ is the sorted input list and _n_ is its length. The outer for loop will have to iterate from _i_ = 1 to _i_ = _n-5_ with a guarantee of failure in finding the desired quadruplet since the lowest element in the desired quadrauplet occurs at index _n-4_. For each iteration of the outer for loop, the remaining two nested inner for loops iterate through the remaining elements to the right of index _i_, looking at all possible ordered pairs _(b,c)_ such that _target - (a+b+c)_ is in the original list. This is an O(n\xB2) search that occurs _within_ each iteration of the outer for loop. It is guaranteed to fail in the worst case for outer loop indices from _i_ = 1 to _i_ = _n-5_. Thus in the worst case this algorithm is O(n\xB3).\n```\nclass Solution:\n def fourSum(self, n: List[int], t: int) -> List[List[int]]:\n \tif not n: return []\n \tn.sort()\n \tL, N, S, M = len(n), {j:i for i,j in enumerate(n)}, set(), n[-1]\n \tfor i in range(L-3):\n \t\ta = n[i]\n \t\tif a + 3*M < t: continue\n \t\tif 4*a > t: break\n \t\tfor j in range(i+1,L-2):\n \t\t\tb = n[j]\n \t\t\tif a + b + 2*M < t: continue\n \t\t\tif a + 3*b > t: break\n \t\t\tfor k in range(j+1,L-1):\n \t\t\t\tc = n[k]\n \t\t\t\td = t-(a+b+c)\n \t\t\t\tif d > M: continue\n \t\t\t\tif d < c: break\n \t\t\t\tif d in N and N[d] > k: S.add((a,b,c,d))\n \treturn S\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com
13
1
['Python', 'Python3']
2
4sum
✅ C++ || WITHOUT USING SET || 100% FAST
c-without-using-set-100-fast-by-9tin_bit-a8q1
INSTEAD OF USING SET FOR REMOVING DUPLICATES WE ARE USING SOME WHILE LOOPS AND IF CONDITIONS:\n\n\nclass Solution {\npublic:\n #define ll long long\n vect
rab8it
NORMAL
2022-06-05T19:17:54.661342+00:00
2022-06-20T15:30:48.073034+00:00
1,082
false
# INSTEAD OF USING SET FOR REMOVING DUPLICATES WE ARE USING SOME WHILE LOOPS AND IF CONDITIONS:\n\n```\nclass Solution {\npublic:\n #define ll long long\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>>ans;\n sort(nums.begin(),nums.end());\n for(ll i=0;i<nums.size();i++){\n if(i>0 && nums[i]==nums[i-1])continue; //REMOVES DUPLICATE IN 1ST INDEX\n ll t=target-nums[i];\n for(ll j=i+1;j<nums.size();j++){\n if(j>i+1 && nums[j]==nums[j-1])continue; //REMOVE DUPLICATE IN 2ND INDEX\n ll s=t-nums[j];\n ll left=j+1,right=nums.size()-1;\n while(left<right){\n ll sum=nums[left] + nums[right];\n if(sum==s){\n ans.push_back({nums[i],nums[j],nums[left],nums[right]});\n while(left<nums.size()-1 && nums[left]==nums[left+1])left++; //REMOVE DUPLICATE IN 3RD INDEX\n while(right>0 && nums[right]==nums[right-1])right--; //REMOVE DUPLICATE IN 4TH INDEX\n left++;\n right--;\n }\n else if(sum<s)left++;\n else right--;\n }\n }\n }\n return ans;\n }\n\n};\n```\n\n![image](https://assets.leetcode.com/users/images/10a8794f-c64c-4561-b4d9-2b7a2524753d_1654456657.7689903.png)\n\n\n\uD83D\uDE4C\uD83D\uDE4C HAPPY CODING !!
12
0
['Two Pointers', 'Binary Search', 'C', 'Binary Tree']
1
4sum
Simple Java Solution, 18ms, O(n^3), HashSet (100% beat)
simple-java-solution-18ms-on3-hashset-10-hrx7
class Solution {\n public List> fourSum(int[] arr, int target) {\n \n Set > set = new HashSet<>();\n Arrays.sort(arr);\n \n
pankaj846
NORMAL
2020-08-08T18:17:22.829811+00:00
2020-08-08T18:17:22.829856+00:00
2,033
false
class Solution {\n public List<List<Integer>> fourSum(int[] arr, int target) {\n \n Set<List<Integer> > set = new HashSet<>();\n Arrays.sort(arr);\n \n for(int i=0; i<arr.length-3; i++){\n for(int j=i+1; j<arr.length-2; j++){\n int left = j+1;\n int right = arr.length-1;\n \n while(left<right){\n int sum = arr[i]+arr[j]+arr[left]+arr[right];\n \n if(sum==target) {\n set.add(Arrays.asList(arr[i],arr[j],arr[left],arr[right]));\n left++;\n right--;\n }\n \n else if(sum<target) left++;\n \n else if(sum>target) right--;\n \n } \n \n }\n \n }\n \n return new ArrayList<>(set);\n }\n}\n
12
0
['Two Pointers', 'Ordered Set', 'Java']
5
4sum
O(n^3) solution is trivial is there any O(n^2logn) algorithm
on3-solution-is-trivial-is-there-any-on2-y47p
Any Better algorithm than O(n^3) time complexity.\n\n public class Solution {\n public List> fourSum(int[] num, int target) {\n Lis
npraveen
NORMAL
2014-10-05T13:52:22+00:00
2014-10-05T13:52:22+00:00
7,155
false
Any Better algorithm than O(n^3) time complexity.\n\n public class Solution {\n public List<List<Integer>> fourSum(int[] num, int target) {\n List<List<Integer>> results = new LinkedList<List<Integer>>();\n if (num == null || num.length < 4)\n return results;\n Arrays.sort(num);\n \n for (int s = 0; s < num.length - 3; s++) {\n if (s > 0 && num[s] == num[s - 1]) continue;\n \n \n for (int e = num.length - 1; e >= s + 3; e--) {\n if (e < num.length - 1 && num[e] == num[e + 1]) continue;\n \n int local = target - num[s] - num[e];\n int j = s + 1;\n int k = e - 1;\n while (j < k) {\n \n if (j > s + 1 && num[j] == num[j - 1]) {\n j++;\n continue;\n }\n if (k < e - 1 && num[k] == num[k + 1]) {\n k--;\n continue;\n }\n \n if ((num[j] + num[k]) > local)\n k--;\n else if ((num[j] + num[k]) < local)\n j++;\n else\n results.add(new ArrayList<Integer>(Arrays.asList(\n num[s], num[j++], num[k--], num[e])));\n }\n }\n }\n return results;\n }\n }
12
0
[]
3
4sum
✅ EASIEST || 💯 BEATS || 🧑‍💻 JAVA || ⭐ TWO POINTERS
easiest-beats-java-two-pointers-by-thaku-6x3g
IntuitionThis problem builds on the "two-sum" and "three-sum" problems. To find four numbers that add up to a target value, we can try a sorted array and use tw
THAKUR_GAURAV_14
NORMAL
2025-02-13T14:43:36.768662+00:00
2025-02-13T14:43:36.768662+00:00
2,477
false
# Intuition This problem builds on the "two-sum" and "three-sum" problems. To find four numbers that add up to a target value, we can try a sorted array and use two nested loops for the first two numbers. For the remaining pair, we can apply a two-pointer approach to find all unique quadruplets. # Approach Sort the Array: Sorting the array helps simplify handling duplicate values and allows the two-pointer technique. Nested Loops: Use two nested loops to pick the first two numbers, nums[i] and nums[j]. Ensure these loops skip duplicates to avoid redundant calculations. Two-Pointer Search: For the remaining two numbers, use two pointers (k starting right after j and l at the end of the array). If the sum of nums[i], nums[j], nums[k], and nums[l] matches the target, add the quadruplet to the result. Adjust pointers k and l to find other potential pairs, ensuring you skip over duplicates. Result Storage: Store each unique quadruplet in a list and return this list of lists. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> ans = new ArrayList<>(); int len = nums.length; Arrays.sort(nums); for (int i = 0; i < len - 3; i++) { if (i > 0 && nums[i - 1] == nums[i]) continue; for (int j = i + 1; j < len - 2; j++) { if (j > i + 1 && nums[j - 1] == nums[j]) continue; int k = j + 1; int l = len - 1; while (k < l) { long sum = nums[i] + nums[j]; sum += nums[k] + nums[l]; if (sum == target) { ans.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l])); k++; l--; while (k < l && nums[k - 1] == nums[k]) k++; while (k < l && nums[l + 1] == nums[l]) l--; } else if (sum < target) k++; else l--; } } } return ans; } } ```
11
2
['Array', 'Two Pointers', 'Sorting', 'Python', 'C++', 'Java']
1
4sum
Python3 | Brute-force > Better > Optimal | Full Explanation
python3-brute-force-better-optimal-full-7hs8s
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
kbbhatt04
NORMAL
2023-06-16T03:27:03.260727+00:00
2023-06-16T03:27:03.260756+00:00
4,209
false
- 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```
11
0
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'Python3']
2
4sum
Similar to 3Sum, Use Two Pointers [Java] Easy-Understand
similar-to-3sum-use-two-pointers-java-ea-xl3u
Problem\n\n> Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all uniqu
junhaowanggg
NORMAL
2019-11-04T02:14:40.211795+00:00
2019-11-04T02:14:40.211845+00:00
2,430
false
## Problem\n\n> Given an array nums of `n` integers and an integer `target`, are there elements `a`, `b`, `c`, and `d` in `nums` such that `a + b + c + d = target`? Find all unique quadruplets in the array which gives the sum of `target`.\n\n**Note:** The solution set must not contain duplicate quadruplets.\n\n**Example:** \n\n```java\nGiven array nums = [1, 0, -1, 0, -2, 2], and target = 0.\n\nA solution set is:\n[\n [-1, 0, 0, 1],\n [-2, -1, 1, 2],\n [-2, 0, 0, 2]\n]\n\nInput: [0, 0, 0, 0], and target = 0.\nOutput: [[0, 0, 0, 0]]\n```\n\n\n## Analysis\n\n### 3Sum + 4Sum\n\nUse two pointers in 3Sum.\n\n```java\npublic List<List<Integer>> fourSum(int[] nums, int target) {\n int n = nums.length;\n // sorting\n Arrays.sort(nums);\n // fourSum\n List<List<Integer>> result = new ArrayList<>();\n for (int i = 0; i < n; ++i) {\n if (i > 0 && nums[i - 1] == nums[i]) continue;\n threeSum(nums, i + 1, n - 1, target - nums[i], result);\n }\n return result;\n}\n \nprivate void threeSum(int[] nums, int lo, int hi, int target, List<List<Integer>> result) {\n int n = nums.length;\n int subLen = hi - lo + 1;\n for (int i = lo; i <= hi; ++i) {\n if (i > lo && nums[i] == nums[i - 1]) continue; // skip same result\n // two pointers\n int j = i + 1, k = hi;\n int t = target - nums[i];\n while (j < k) { // each element is only used once\n if (nums[j] + nums[k] < t) {\n ++j;\n } else if (nums[j] + nums[k] > t) {\n --k;\n } else { // equal\n result.add(Arrays.asList(nums[lo - 1], nums[i], nums[j], nums[k]));\n ++j;\n --k;\n while (j < k && nums[j] == nums[j - 1]) j++; // skip same result\n while (j < k && nums[k] == nums[k + 1]) k--; // skip same result\n }\n }\n }\n}\n```\n\n**Time:** `O(N^3)`\n**Space:** `O(1)`\n\n\n\n
11
0
['Java']
1
4sum
Handle KSum yet still accepted with best performance 16ms in C++
handle-ksum-yet-still-accepted-with-best-5hlu
class Solution {\n private:\n const int K = 4;\n int size = 0;\n void search(vector<int>& nums, int pos, int k, int target, vector<int>&
lhearen
NORMAL
2016-06-20T09:10:23+00:00
2016-06-20T09:10:23+00:00
2,637
false
class Solution {\n private:\n const int K = 4;\n int size = 0;\n void search(vector<int>& nums, int pos, int k, int target, vector<int>& v, vector<vector<int>>& vv)\n {\n if(k == 2)\n {\n int l = pos, r = size-1;\n while(l < r)\n {\n int t = nums[l]+nums[r];\n if(t > target) r--;\n else if(t < target) l++;\n else \n {\n v[K-2] = nums[l++];\n v[K-1] = nums[r--];\n vv.push_back(v);\n while(l<r && nums[l]==nums[l-1]) l++; //avoid duplicates;\n while(l<r && nums[r]==nums[r+1]) r--; //avoid duplicates;\n }\n }\n }\n else\n {\n for(int top = size-k; pos <= top; ++pos)\n {\n int sum = 0;\n for(int i = 0; i < k; i++) sum += nums[pos+i]; \n if(sum > target) break; //avoid futile searching;\n sum = nums[pos];\n for(int i = 0; i < k-1; ++i) sum += nums[size-1-i];\n if(sum < target) continue; //avoid futile searching;\n v[K-k] = nums[pos];\n search(nums, pos+1, k-1, target-nums[pos], v, vv);\n while(pos<=top && nums[pos+1]==nums[pos]) pos++; //avoid duplicates;\n }\n }\n }\n public:\n //AC - 16ms - handle kSum;\n vector<vector<int>> fourSum(vector<int>& nums, int target) \n {\n sort(nums.begin(), nums.end());\n size = nums.size();\n vector<vector<int>> vv;\n vector<int> v(K, 0);\n search(nums, 0, K, target, v, vv);\n return vv;\n }\n };
11
1
['Depth-First Search', 'C++']
1
4sum
0ptimized Approach | | Java | |
0ptimized-approach-java-by-rkroy-e9cd
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 a
RkRoy
NORMAL
2023-04-01T17:26:36.144581+00:00
2023-04-01T17:26:36.144675+00:00
4,794
false
# 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```
10
0
['Array', 'Two Pointers', 'Java']
2
4sum
✔️ 100% Fastest Swift Solution
100-fastest-swift-solution-by-sergeylesc-x6us
\nclass Solution {\n func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] {\n let sorted = nums.sorted()\n var res: [[Int]] = []\n var
sergeyleschev
NORMAL
2022-03-31T05:46:55.690925+00:00
2022-03-31T05:46:55.690977+00:00
757
false
```\nclass Solution {\n func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] {\n let sorted = nums.sorted()\n var res: [[Int]] = []\n var i = 0\n \n while i < sorted.count - 3 {\n if i > 0, sorted[i] == sorted[i - 1] { i += 1; continue }\n var j = i + 1\n while j < sorted.count - 2 {\n if j - 1 > i, sorted[j] == sorted[j - 1] { j += 1; continue }\n var k = j + 1\n var l = sorted.count - 1\n \n while k < l {\n let sum = sorted[i] + sorted[j] + sorted[k] + sorted[l]\n if sum == target {\n if k - 1 > j, sorted[k] == sorted[k - 1] { k += 1; continue }\n res.append([sorted[i], sorted[j], sorted[k], sorted[l]])\n k += 1\n }\n if sum < target {\n k += 1\n } else {\n l -= 1\n }\n }\n j += 1\n }\n i += 1\n }\n\n return res\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful.
10
0
['Swift']
0
4sum
Java simple solution
java-simple-solution-by-saurabh_95-73wr
\'\'\'\nclass Solution {\n public List> fourSum(int[] nums, int target) {\n List> result=new ArrayList<>();\n if(nums==null || nums.length<4){\
saurabh_95
NORMAL
2021-07-27T09:13:46.291507+00:00
2021-07-27T09:13:46.291541+00:00
996
false
\'\'\'\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n List<List<Integer>> result=new ArrayList<>();\n if(nums==null || nums.length<4){\n return result;\n }\n Arrays.sort(nums);\n int n=nums.length;\n \n for(int i=0;i<n-3;i++){\n for(int j=i+1;j<n-2;j++){\n int low=j+1;\n int high=n-1;\n \n while(low<high){\n int sum=nums[i]+nums[j]+nums[low]+nums[high];\n if(sum==target){\n List<Integer>list=new ArrayList<>();\n list.add(nums[i]);\n list.add(nums[j]);\n list.add(nums[low]);\n list.add(nums[high]);\n \n \n if(result.contains(list)==false){\n result.add(list);\n }\n low++;\n high--;\n }\n else if(sum<target){\n low++;\n }\n else{\n high--;\n }\n }\n }\n }\n return result;\n \n }\n}\n\'\'\'
10
3
['Java']
1
4sum
JavaScript solution with explanation
javascript-solution-with-explanation-by-80amd
We will have 2 loops for 2 elements of quadruplets. Lets say for 2 loops we will use i and j for the interations. For finding next 2 elements we will use 2 poin
nbp343
NORMAL
2021-07-17T07:39:34.122643+00:00
2021-07-17T07:46:17.227329+00:00
1,315
false
We will have 2 loops for 2 elements of quadruplets. Lets say for 2 loops we will use i and j for the interations. For finding next 2 elements we will use 2 pointer method.\nIn 2 pointer method we will have 2 pointers left and right. Initially we will set left pointer as j+1 and right as length-1.\n\nWe will check the sum (nums[i] + nums[j] + nums[left] + nums[right]). If it is equal to target then we will push that quadruplets to result array. We need to increase left and right pointer. Because only changing one pointer will always give different sum (not equal to target)\nIf sum is less than target then we need to increase only left pointer(not the right pointer) because we need to increase the sum value to match it with target value. If we decrease right pointer, we will have smaller element in the combination which will not increase overall sum.(Remember the array is sorted)\nIf sum is greater than the target then we need to reduce right pointer (as per above logic)\n\nTo avoid duplicate entries, we need to take care whether each element is not repeating itself for same combinations of the other elements. Lets say we have array=[3,3,4,4,4,1,1,5] and target=16\n``` \n//first interation \n [3,3,4,4,4,1,1,5] \n i j l r\n //here sum is 15 which is less than 16. we need to increment the left point. \n //As next element is also same as current element for left pointer we don\'t need to consider that combination. \n //We need to increment the left pointer until we get different combination. \n \n //next interation should be\n [3,3,4,4,4,1,1,5] \n i j l r\n```\n\nThis way we need to avoid duplicates for every elements. As the array is sorted all the same elements will be side by side and we can easily avoid using same value for the perticular element.\n \n```\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[][]}\n */\nvar fourSum = function(nums, target) {\n nums.sort((a,b)=>a-b) //First sort the array in ascending order\n let len = nums.length;\n let left=0, right=0, sum=0;\n let result = [];\n for(let i=0; i<len-3; i++){\n for(let j=i+1; j<len-2; j++){\n left = j+1;\n right = len-1;\n while(left < right){\n sum = nums[i] + nums[j] + nums[left] + nums[right];\n if(sum === target){\n result.push([nums[i], nums[j], nums[left], nums[right]])\n while(nums[left]===nums[left+1]) left++; //To avoid same values for left pointer\n while(nums[right]===nums[right-1]) right--; //To avoid same values for right pointer\n left++;\n right--;\n } else if (sum < target){\n left++;\n } else {\n right--;\n }\n }\n while(nums[j]===nums[j+1]) j++;\n }\n while(nums[i]===nums[i+1]) i++;\n }\n return result;\n};\n```\n\nTime complexity will be O(n^3) as there are 2 loops and in worst case left pointer will go till end of the array.\nSpace complexity will be O(1) as we are not taking any extra space to store anything.\n
10
0
['Two Pointers', 'JavaScript']
2
4sum
C++ Solution, 8ms, beats 97%
c-solution-8ms-beats-97-by-pooja0406-m7c5
Runtime: 8 ms, faster than 97.93% of C++ online submissions for 4Sum.\nMemory Usage: 8.9 MB, less than 100.00% of C++ online submissions for 4Sum.\n\n```\nclass
pooja0406
NORMAL
2019-11-01T16:11:29.500674+00:00
2019-11-01T16:11:29.500729+00:00
1,248
false
Runtime: 8 ms, faster than 97.93% of C++ online submissions for 4Sum.\nMemory Usage: 8.9 MB, less than 100.00% of C++ online submissions for 4Sum.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n \n vector<vector<int>> res;\n sort(nums.begin(), nums.end());\n \n int n = nums.size();\n for(int i=0; i<n-3; i++)\n {\n if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target) break;\n if(nums[i]+nums[n-1]+nums[n-2]+nums[n-3] < target) continue;\n \n for(int j=i+1; j<n-2; j++)\n {\n if(nums[j]+nums[j+1]+nums[j+2] > target - nums[i]) break;\n if(nums[j]+nums[n-1]+nums[n-2] < target - nums[i]) continue;\n int newTarget = target - nums[i] - nums[j];\n int start = j+1;\n int end = n-1;\n \n while(start < end)\n {\n if(nums[start] + nums[end] < newTarget)\n start++;\n else if(nums[start] + nums[end] > newTarget)\n end--;\n else\n {\n res.push_back(vector<int> {nums[i], nums[j], nums[start], nums[end]});\n start++;\n end--;\n while(start < end && nums[start] == res.back()[2]) start++;\n while(start < end && nums[end] == res.back()[3]) end--;\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 res;\n }\n};
10
1
[]
4
4sum
Python || Beginners solution || Easy
python-beginners-solution-easy-by-its_it-lyl5
\n# Code\n\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n ans = set()\n nums.sort()\n for i in
its_iterator
NORMAL
2022-10-20T11:28:18.878665+00:00
2022-10-20T11:28:18.878697+00:00
3,364
false
\n# Code\n```\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n ans = set()\n nums.sort()\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n k,l = j+1,len(nums)-1\n while k<l:\n s = nums[i]+nums[j]+nums[k]+nums[l]\n if s == target:\n ans.add((nums[i],nums[j],nums[k],nums[l]))\n l-=1\n k+=1\n elif s > target:\n l-=1\n else:\n k+=1\n \n return ans\n```
9
0
['Python3']
4
4sum
Simple Hashmap Implementation || C++|| Intution Explained
simple-hashmap-implementation-c-intution-ys0r
Intution : We take a unorederd map and then calculate 2 sum of all the possiblities of i and j pair and store it in the map besides there indexes and then we ru
sahil_rout
NORMAL
2021-11-12T17:34:20.774316+00:00
2021-11-13T17:54:22.210972+00:00
1,008
false
Intution : We take a unorederd map and then calculate 2 sum of all the possiblities of i and j pair and store it in the map besides there indexes and then we run a loop and for every i and j we do target - arr[i]-arr[j] and then try to find it in the map if it exists that means this is a possible answer qudraplet .\n\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n vector<vector<int>> ans;\n int n=nums.size();\n if(n<4) return ans;\n sort(nums.begin(),nums.end());\n unordered_map<int,vector<pair<int,int>>> mp;\n for(int i=0;i<n-1;i++)\n {\n for(int j=i+1;j<n;j++)\n {\n mp[nums[i]+nums[j]].push_back({i,j});//making 2 sum map\n }\n }\n for(int i=0;i<n-1;i++)\n {\n if(i>0 and nums[i]==nums[i-1]) continue;\n for(int j=i+1;j<n;j++)\n {\n if(j>i+1 and nums[j]==nums[j-1]) continue;\n int sum=target-nums[i]-nums[j];\n if(mp.find(sum)!=mp.end())\n {\n for(auto it : mp[sum])\n {\n int k=it.first;\n int l=it.second;\n if(k>j){\n if(!ans.empty()&& ans.back()[0]==nums[i]&&ans.back()[1]==nums[j]&&ans.back()[2]==nums[k]&&ans.back()[3]==nums[l]) continue;\n vector<int> temp={nums[i],nums[j],nums[k],nums[l]};\n ans.push_back(temp);\n }\n }\n }\n }\n }\n \n return ans;\n }\n};\n```\n**Up Vote this pls if you understood**
9
0
['C', 'C++']
1
4sum
Python Generalized Soln for ksum with explanation
python-generalized-soln-for-ksum-with-ex-v5zi
Lets generalize 1sum,2sum,3sum,4sum... problems into ksum\n1)As we know we that 1sum is simply as returning the elements in the lists which are equal to target
irfanahmed
NORMAL
2020-04-26T18:03:38.118748+00:00
2020-04-26T18:11:41.176963+00:00
1,296
false
Lets generalize 1sum,2sum,3sum,4sum... problems into ksum\n1)As we know we that 1sum is simply as returning the elements in the lists which are equal to target\n2)First we sort the given list then\n3)We can solve ksums where k>2 by reducing them to 2sum recursively\n4)Where we solve 2sum problem with two pointer approach\n```\nres = []\ni = begin #left pointer\nj = len(nums) - 1 #right pointer\nwhile i < j: #where pointers dont cross each other\n\tif nums[i] + nums[j] == target: \n\t\tres.append([nums[i], nums[j]]) # if found then nums[i] and nums[j] pair are one of the results hence we store these as pair\n\t\twhile i < j and nums[i] == nums[i + 1]: #to remove redundant pairs\n\t\t\ti += 1\n\t\twhile i < j and nums[j] == nums[j - 1]: #to remove redundant pairs\n\t\t\tj -= 1\n\t\ti += 1\n\t\tj -= 1\n\t\t#as we found the pair we move left pointer forward and right pointer backward in list\n\telif nums[i] + nums[j] > target:\n\t\tj -= 1\n\t\t#As the sum is > target we move right pointer holding larger value to 1 step left\n\telse:\n\t\ti += 1\n\t\t#As the sum is < target we move left pointer smaller value to 1 step right\n\n```\n\n5)For 3sum we iterate over each element and find 2sum solution .ie if current index is i and element is nums[i]\n\twe find 2sum solution for target = target- nums[i] in list from index i+1 to i = len(nums)-1 and then add nums[i] to the solution\n6)For ksum we iterate over each element and find (k-1)sum solution recursively.\n\n```\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n def helper(nums,target,ksum,begin):\n if begin >= len(nums): #base condition\n return []\n if ksum == 2: \n\t\t\t #two pointer approach as we do in 2sum problem\n res = []\n i = begin\n j = len(nums) - 1\n while i < j:\n if nums[i] + nums[j] == target:\n res.append([nums[i], nums[j]])\n while i < j and nums[i] == nums[i + 1]:\n i += 1\n while i < j and nums[j] == nums[j - 1]:\n j -= 1\n i += 1\n j -= 1\n elif nums[i] + nums[j] > target:\n j -= 1\n else:\n i += 1\n return res\n res = [] \n for i in range(begin, len(nums) - ksum + 1):\n if i > begin and nums[i] == nums[i - 1] or nums[i] + nums[-1] * (ksum - 1) < target:\n continue\n\t\t\t\t\t# the first condition is to remove Duplicates \n\t\t\t\t\t# the second Condition is that if we consider element nums[i] whether we get required target or not\n\t\t\t\t\t#ie if we consider nums[i] which is smallest in current ksum size windown and ksum-1 times of largest number in the nums and still we get sum < target the we do not need to consider nums[i]\n if nums[i] + nums[i + 1] * (ksum - 1) > target:\n break\n\t\t\t\t\t#Same as above if nums[i] + nums[i + 1] * (ksum - 1) > target it means that remaining elements after i algo give result > target hence we exit from the loop\n r = helper(nums, target - nums[i], ksum - 1, i + 1)\n for elm in r:\n elm.insert(0,nums[i])\n\t\t\t\t\t#We insert current nums[i] to the result of ksum-1 result\n for elm in r:\n res.append(elm)\n\t\t\t\t\t#we store result of size ksum \n return res\n\n nums.sort()\n\t\tksum = 4\n\t\t#ksum = 4 As we are finding 4sum here\n\t\t# For generailized case \n\t\t#if ksum <1: return []\n\t\t#if ksum ==1:\n\t\t\t# return [target]*nums.count(target)\n return helper(nums, target, ksum, 0)\n
9
0
[]
0
4sum
Python easy to understand ~25 lines - Dictionary - O(n^3)
python-easy-to-understand-25-lines-dicti-uv38
\ntwo_sums = {}\nfor i in range(len(nums)):\n\tfor j in range(i + 1, len(nums)):\n\t\tif (target - nums[i] - nums[j]) in two_sums:\n\t\t\ttwo_sums[target - nums
aadith
NORMAL
2019-10-16T21:27:45.725490+00:00
2019-10-16T21:50:06.616785+00:00
1,662
false
```\ntwo_sums = {}\nfor i in range(len(nums)):\n\tfor j in range(i + 1, len(nums)):\n\t\tif (target - nums[i] - nums[j]) in two_sums:\n\t\t\ttwo_sums[target - nums[i] - nums[j]].append([i, j])\n\t\telse:\n\t\t\ttwo_sums[target - nums[i] - nums[j]] = [[i, j]]\n\nfour_sums = []\nfor i in range(len(nums)):\n\tfor j in range(i + 1, len(nums)):\n\t\ttemp = nums[i] + nums[j]\n\t\tif temp in two_sums:\n\t\t\tfor twos in two_sums[temp]:\n\t\t\t\tif not(twos[0] == i or\n\t\t\t\ttwos[0] == j or\n\t\t\t\ttwos[1] == i or\n\t\t\t\ttwos[1] == j):\n\t\t\t\t\tfour_sums.append([nums[i], nums[j], nums[twos[0]], nums[twos[1]]])\n\nreturn sorted(list(set(map(lambda x: tuple(sorted(x)), four_sums))))\n```\n\n* Highly suggest you solve [Two Sum](https://leetcode.com/problems/two-sum/) and maybe even [3Sum](https://leetcode.com/problems/3sum/) first\n* How do you break up a 4Sum problem?\n\t* A simple approach is to find a pair of numbers first\n\t* Then find another pair such that the set of those 4 numbers adds up to `target`\n\n\n* First dictionary iterates through the array and adds all `i, j` pairs to a dictionary\n* Key in this case will be `target - nums[i] - nums[j]`\n\t* Why `target - nums[i] - nums[j]`? `target` in the first example in the code desc. is 0. `i - j` for say, 3rd (i) and 2nd (j) index is 1\n\t* Essentially, this is `target` *without* `nums[i]` and `nums[j]` i.e the number your second pair that you find later needs to add up to\n\t* This is because you have *removed* `nums[i]` and `nums[j]` from target\n\t* In a nutshell, you say that an entry `x` in your dictionary represents how much of `target` you need to find if you take an entry `i, j` from the list that is held in that entry\'s value\n\n* After you build the dictionary, iterate through the array of numbers\n* For each number, iterate through each number *after* it in the array (O(n^2))\n* Add those two numbers up\n\t* See a pattern here? If the sum of these two numbers is in the dictionary we built, you know every permutation of two *other* numbers in the array that give you `target` when you add them up\n\t* Look at every pair of those and ignore pairs where one of the indices is the same\n\t\t* If the index is the same, you are looking at the same element. You need 4 different elements to add up to `target`\n\t* Record all quadruplets this way\n\n\n* Sort quadruplets and then sort the list of quadruplets\n* Why do I have so many calls in the last line?\n\t* From right to left:\n\t\t* `sorted(x)` sorts the quadruplet\n\t\t* `tuple(sorted(x))` converts the sorted quadruplet into a tuple so it\'s hashable\n\t\t* `map` this for every element in `four_sums` i.e every quadruplet\n\t\t* Convert the list of quadruplets into a `set` so you only have unique elements\n\t\t\t* This is why we had to `tuple`-fy every quadruplet - so we can hash it\n\t\t* Convert said set of quadruplets into a `sorted` `list`\n* Ta-da!
9
0
['Python3']
0
4sum
C# same as 3SUM
c-same-as-3sum-by-bacon-p9cn
\npublic class Solution {\n public IList<IList<int>> FourSum(int[] nums, int target) {\n var n = nums.Length;\n Array.Sort(nums);\n\n va
bacon
NORMAL
2019-04-20T18:25:24.772465+00:00
2019-04-20T18:25:24.772502+00:00
906
false
```\npublic class Solution {\n public IList<IList<int>> FourSum(int[] nums, int target) {\n var n = nums.Length;\n Array.Sort(nums);\n\n var result = new List<IList<int>>();\n\n for (int i = 0; i < n; i++) {\n if (i > 0 && nums[i - 1] == nums[i]) continue;\n for (int j = i + 1; j < n; j++) {\n if (j > i + 1 && nums[j - 1] == nums[j]) continue;\n var left = j + 1;\n var right = n - 1;\n\n while (left < right) {\n var sum = nums[i] + nums[j] + nums[left] + nums[right];\n if (sum == target) {\n result.Add(new List<int>() { nums[i], nums[j], nums[left], nums[right] });\n\n while (left < right && nums[left] == nums[left + 1]) left++;\n while (left < right && nums[right] == nums[right - 1]) right--;\n \n left++;\n right--;\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n }\n }\n }\n\n return result;\n }\n}\n```
9
0
[]
3
4sum
12ms KSum, c++ code
12ms-ksum-c-code-by-sganje-v8ff
Thanks to the posts from others, it really helped me understand the problem! \nI really liked @rikimberley's example for validity checking at levels of K higher
sganje
NORMAL
2016-07-10T23:43:26.823000+00:00
2018-08-28T05:40:46.527690+00:00
2,277
false
Thanks to the posts from others, it really helped me understand the problem! \nI really liked @rikimberley's example for validity checking at levels of K higher than 2 and I liked the approaches I've seen for turning the problem into a KSum problem. Now I won't have to re-write my answer if they make a 5 sum problem!\n\n```\nclass Solution {\nprivate:\n // Valid for K >= 2\n void KSum(int k, vector<int>& nums, int l, int r, int target, vector<vector<int>>& retVal, vector<int>& cur, int ci ) \n {\n int i, mn, mx;\n int km1 = k - 1;\n\n if ( r-l+1 < k ) return;\n \n while ( l < r )\n {\n mn = nums[l];\n mx = nums[r];\n \n // If K minus 1 largest + min < target, move to larger\n if ( ( mn + km1*mx ) < target ) l++;\n // If K minus 1 smaller + max > target, move to smaller\n else if ( ( km1*mn + mx ) > target ) r--;\n // If K * min > target, stop looking\n else if ( k*mn > target ) break;\n // If K * min == target, reached the threshold, check then stop looking\n else if ( k*mn == target )\n {\n if ( ( l + km1 <= r ) && ( mn == ( nums[l+km1] ) ) )\n {\n for ( i = 0; i < k; i++ ) cur[ci+i] = mn;\n retVal.push_back( cur );\n }\n break;\n }\n // If K * max < target, stop looking\n else if ( k*mx < target ) break;\n // If K * max == target, reached the threshold, check then stop looking\n else if ( k*mx == target )\n {\n if ( ( l <= r - km1 ) && ( mx == ( nums[r-km1] ) ) )\n {\n for ( i = 0; i < k; i++ ) cur[ci+i] = mx;\n retVal.push_back( cur );\n }\n break; \n }\n // If K == 2, we found a match!\n else if ( k == 2 )\n {\n cur[ci] = mn;\n cur[ci+1] = mx;\n retVal.push_back( cur );\n l++;\n while ( ( l < r ) && ( nums[l] == mn ) ) l++;\n r--;\n while ( ( l < r ) && ( nums[r] == mx ) ) r--;\n }\n // Otherwise, convert the problem to a K-1 problem\n else\n {\n cur[ci] = mn;\n KSum( km1, nums, ++l, r, target - mn, retVal, cur, ci+1 );\n while ( ( l < r ) && ( nums[l] == nums[l-1] ) ) l++;\n }\n }\n }\n\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) \n {\n vector<vector<int>> lRetVal;\n vector<int> lQuad( 4, 0 ); // Pre-allocate the size of the result\n\n // Sort to provide a mechanism for avoiding duplicates\n sort( nums.begin(), nums.end() );\n \n KSum( 4, nums, 0, nums.size()-1, target, lRetVal, lQuad, 0 );\n\n return( lRetVal ); \n }\n};
9
0
[]
1
4sum
4 Sum - Easy C++ Solution 100% Beat Solution
4-sum-easy-c-solution-100-beat-solution-esxm3
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
tushargupta17042003
NORMAL
2024-04-01T11:46:02.964355+00:00
2024-04-01T11:46:02.964386+00:00
1,471
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nT.C = $$O(n^3)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nS.C = $$O(no. of quards)$$ this is for returning ans but actually $$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 vector<vector<int>>ans;\n sort(nums.begin(),nums.end());\n\n for(int i=0; i<n; i++){\n if(i>0 && nums[i] == nums[i-1]) continue;\n for(int j = i+1; j<n; j++){\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 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){\n k++;\n }\n else{\n l--;\n }\n }\n }\n }\n return ans;\n }\n};\n```\n![Screenshot 2024-03-29 010953.png](https://assets.leetcode.com/users/images/81ac92af-476a-48ea-ac7b-1515e3f58b87_1711971953.7556007.png)\n
8
0
['C++']
0
4sum
Optimised Two-Pointer Approach; From 20 ms to 6 ms
optimised-two-pointer-approach-from-20-m-rroa
This is my journey from optimising the normal two pointer approach from 20 ms to hell 6 ms! \n\n\n\n\n# Intuition\nIt happens so from handling cases of redundan
whathappenstoaryan
NORMAL
2024-03-09T14:24:20.477196+00:00
2024-03-09T14:32:30.007497+00:00
1,821
false
This is my journey from optimising the normal two pointer approach from 20 ms to hell 6 ms! \n\n![Screenshot 2024-03-09 at 7.39.45 PM.png](https://assets.leetcode.com/users/images/c736609f-0473-4ece-8723-b7c876ca1550_1709994682.1960773.png)\n\n\n# Intuition\nIt happens so from handling cases of redundant iterations.\nFor example,\nYou break out of the first loop if target is greater than zero and first four elements sum from first index is greater than target.\nThere are two more conditions for breaking if target is less or another - is equal to zero.\n\nThere are soo many and I explain them properly with comments.\n\n# Approach\nI present you the speciifc section for optimising.\n```\n for (int i = 0; i < n - 3; i++) {\n // Skip duplicates for the first element\n if (i > 0 && nums[i] == nums[i - 1]) {\n continue; \n }\n // Early exit if the sum of the first four smallest elements is greater than the target (for positive target)\n if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target && target > 0) {\n break;\n }\n // Early exit if the sum of the first four smallest elements is greater than the target (for negative target)\n if(nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target && target < 0 && i + 4 < n && nums[i + 4] > 0) {\n break;\n }\n // Early exit if the target is zero and there are positive numbers after the first four smallest elements\n if(target == 0 && i + 4 < n && nums[i + 4] > 0 && nums[i] > 0) {\n break; \n }\n // Early continue if the sum of the first element and the three largest elements is less than the target (for positive target)\n if ((long)nums[i] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target && target > 0) {\n continue;\n }\n // Iterate through array for potential second element of quadruplet\n for (int j = i + 1; j < n - 2; j++) {\n // Skip duplicates for the second element\n if (j > i + 1 && nums[j] == nums[j - 1]) {\n continue; \n }\n // Early continue if the sum of the first two elements and the two largest elements is less than the target (for non-negative target)\n if ((long)nums[i] + nums[j] + nums[n - 1] + nums[n - 2] < target && target >= 0) {\n continue;\n```\n\n# Complexity\n- Time complexity:\nSame as normal - 0(n^3)\n- Space complexity:\n0(1)\n\n# Code\n```\nimport java.util.*;\n\nclass Solution {\n public List<List<Integer>> fourSum(int[] nums, int target) {\n Arrays.sort(nums); // Sort the input array to simplify the search\n \n List<List<Integer>> result = new ArrayList<>(); // List to store the quadruplets\n \n int n = nums.length;\n \n // Iterate through the array, fixing the first element of the quadruplet\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 \n // Early exit condition if the sum of the first four elements is greater than the target (for positive targets)\n if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target && target > 0) {\n break;\n }\n \n // Early exit condition if the sum of the first four elements is greater than the target (for negative targets with positive elements)\n if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target && target < 0 && i + 4 < n && nums[i + 4] > 0) {\n break;\n }\n \n // Early exit condition if the target is zero and there are positive numbers after the first four smallest elements\n if (target == 0 && i + 4 < n && nums[i + 4] > 0 && nums[i] > 0) {\n break; \n } \n \n // Early continue if the sum of the first element and the three largest elements is less than the target\n if ((long) nums[i] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target && target > 0) {\n continue;\n }\n \n // Iterate through the remaining elements using a two-pointer approach\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 \n // Early exit condition if the target is zero and there are positive numbers after the first two smallest elements\n if (j < n - 1 && nums[j] > 0 && nums[j + 1] > 0 && target - nums[i] == 0) {\n break;\n }\n \n // Early exit condition if the sum of the first three elements and the largest element is greater than the target\n if (target > 0 && nums[i] + nums[j] + nums[j + 1] > target - nums[i]) {\n break;\n }\n \n // Early exit condition if the sum of the first three elements and the largest positive element is less than the target\n if (target < 0 && nums[i] + nums[j] + nums[j + 1] > target - nums[i] && j + 2 < n && nums[j + 2] > 0) {\n break;\n }\n \n // Early continue if the sum of the first two elements and the two largest elements is less than the target\n if ((long) nums[i] + nums[j] + nums[n - 1] + nums[n - 2] < target && target >= 0) {\n continue;\n }\n\n int left = j + 1; // Initialize left pointer\n int right = n - 1; // Initialize right pointer\n \n // Two-pointer approach to find the remaining two elements\n while (left < right) {\n long sum = (long) nums[i] + nums[j] + nums[left] + nums[right]; // Calculate the sum\n \n if (sum == target) { // Quadruplet found\n result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); // Add quadruplet to result\n \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 \n left++; // Move left pointer\n right--; // Move right pointer\n } else if (sum < target) { // If sum is less than target, move left pointer to increase sum\n left++;\n } else { // If sum is greater than target, move right pointer to decrease sum\n right--;\n }\n }\n }\n }\n \n return result; // Return the list of quadruplets\n }\n}\n\n\n```\n\nBelow is the history of optimising from 20 ms to 6 gradually haha\n\n![Screenshot 2024-03-09 at 7.40.38 PM.png](https://assets.leetcode.com/users/images/3ce5d71b-f119-4b63-8fa0-e7f1569e0bf8_1709994745.426009.png)\n\n
8
0
['Two Pointers', 'Java']
1
4sum
Most optimal solution with explanation using two pointers approach | C++ and JAVA code
most-optimal-solution-with-explanation-u-apwc
\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 a
priyanshu11_
NORMAL
2023-07-06T16:46:56.470466+00:00
2023-07-06T16:46:56.470502+00:00
3,477
false
\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```
8
0
['Array', 'Two Pointers', 'Sorting', 'C++', 'Java']
0
4sum
C++ Solution : 4Sum || Two Pointer Approach || Using Two Sum || O(N^3)
c-solution-4sum-two-pointer-approach-usi-vsav
1. Two Pointer Approach\n Pre-requisites - Two Sum , 3Sum (For better understanding)\n Time Complexity - O(N^3)\n\nclass Solution {\npublic:\n vector<vector<
itsyashkumar23
NORMAL
2022-09-27T19:04:09.660427+00:00
2022-09-27T19:04:09.660465+00:00
1,999
false
**1. Two Pointer Approach**\n* Pre-requisites - [Two Sum](https://leetcode.com/problems/two-sum/) , [3Sum](https://leetcode.com/problems/3sum//) (For better understanding)\n* Time Complexity - O(N^3)\n```\nclass Solution {\npublic:\n vector<vector<int>> fourSum(vector<int>& nums, int target) {\n int n = nums.size();\n //start & end pointers\n int s, e;\n //initializing answer vector\n vector<vector<int>> ans;\n //initializing set\n set<vector<int>> st;\n sort(nums.begin(), nums.end());\n \n //Edge Case\n if(n < 4){\n return ans;\n }\n \n // fixing first element of quadruplets \n for(int i = 0; i < n; i++){\n // fixing second element of quadruplets \n for(int j = i+1; j < n; j++){\n // now we are left with 2SUM problem\n //intializing start and end\n s = j + 1;\n e = n - 1;\n \n while(s < e){\n \n if((long) nums[i] + nums[j] + nums[s] + nums[e] == target){\n st.insert({nums[i], nums[j], nums[s], nums[e]});\n s++, e--;\n }\n else if((long) nums[i] + nums[j] + nums[s] + nums[e] > target){\n e--;\n }\n else{\n s++;\n }\n }\n }\n }\n \n // storing elements of set into ans\n for(auto i: st)\n ans.push_back(i);\n \n return ans;\n }\n};\n```\n\nPlease Upvote if is helps :)
8
0
['Two Pointers', 'C++']
3
4sum
C++ 4ms <99.88%, 9.1MB <94.74% 2 pointers within 2 for loops
c-4ms-9988-91mb-9474-2-pointers-within-2-lzss
Runtime: 4 ms, faster than 99.88% of C++ online submissions for 4Sum.\n* Memory Usage: 9.1 MB, less than 94.74% of C++ online submissions for 4Sum.\n\n\nstatic
jonlist
NORMAL
2019-11-29T23:30:16.618657+00:00
2019-11-29T23:30:16.618692+00:00
1,194
false
* Runtime: 4 ms, faster than 99.88% of C++ online submissions for 4Sum.\n* Memory Usage: 9.1 MB, less than 94.74% of C++ online submissions for 4Sum.\n\n```\nstatic auto x = []() {ios_base::sync_with_stdio(false); cin.tie(NULL); return NULL; }();\n\nclass Solution {\npublic:\nvector< vector<int> > fourSum(vector<int>& nums, int target) {\n\tvector< vector<int> > result;\n\tsize_t n = nums.size();\n\tif (n < 4) \treturn result;\n\n\n\tsort(nums.begin(), nums.end());\n\tfor (int i = 0; i < n-3; ++i) {\n\t\tif (target <= 0 && nums[i] > 0) break;\n\n\t\tif (nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break;\n\t\tif (nums[i] + nums[n-3] + nums[n-2] + nums[n-1] < target) continue; \n\t\tif (i > 0 && nums[i] == nums[i-1]) continue;\n\n\t\tfor (int j = i+1; j < n - 2; ++j) {\n\t\t\tif (nums[i] + nums[j] + nums[j+1] + nums[j+2] > target) break;\n\t\t\tif (nums[i] + nums[j] + nums[n-2] + nums[n-1] < target) continue; \n\t\t\tif (j > i+1 && nums[j] == nums[j-1]) continue;\n\n\t\t\tint left = j+1, right = n-1;\n\t\t\twhile (left < right) {\n\t\t\t\tint sum = nums[i] + nums[j] + nums[left] + nums[right];\n\t\t\t\tif (sum == target) \n {\n\t\t\t\t\tresult.push_back({nums[i], nums[j], nums[left], nums[right]});\n\t\t\t\t\tint last_left = nums[left], last_right = nums[right];\n\t\t\t\t\twhile (left < right && nums[left] == last_left) ++left;\n\t\t\t\t\twhile (left < right && nums[right] == last_right) --right;\n\t\t\t\t} \n else if (sum < target) { ++left; } \n else { --right; }\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n};\n```
8
1
['C++']
2