Find All Four Sum Numbers | Practice | GeeksforGeeks

Given an array of integers and another number. Find all the unique quadruple from the given array that sums up to the given number.
Example 1:
Input:
N = 5, K = 3
A[] = {0,0,2,1,1}
Output: 0 0 1 2 $
Explanation: Sum of 0, 0, 1, 2 is equal
to K.

Example 2:
Input:
N = 7, K = 23
A[] = {10,2,3,4,5,7,8}
Output: 2 3 8 10 $2 4 7 10 $3 5 7 8 $
Explanation: Sum of 2, 3, 8, 10 = 23,
sum of 2, 4, 7, 10 = 23 and sum of 3,
5, 7, 8 = 23.
Your Task:
You don't need to read input or print anything. Your task is to complete the function fourSum() which takes the array arr[] and the integer k as its input and returns an array containing all the quadruples in a lexicographical manner. Also note that all the quadruples should be internally sorted, ie for any quadruple [q1, q2, q3, q4] the following should follow: q1 <= q2 <= q3 <= q4.  (In the output each quadruple is separate by $. The printing is done by the driver's code)
Expected Time Complexity: O(N3).
Expected Auxiliary Space: O(N2).
Constraints:
1 <= N <= 100
-1000 <= K <= 1000
-100 <= A[] <= 100
 
0
ashwini12920034 days ago
#include<stdio.h>
void main()
{   int a,b,c,d;
   printf("enter the four values to be added");
scanf("%d",&a,&b,&c,&d);
sum=a+b+c+d;
printf("the sum of four numbers are",sum)
}
0
sahum67031 week ago
vector<vector<int> > fourSum(vector<int> &arr, int k) {
        sort(arr.begin(),arr.end());
        vector<vector<int>> ans;
        unordered_map<int,int> mp;
        
        set<vector<int>> st;
        int n=arr.size();
        for(int i=0;i+3<n;i++){
            for(int j=i+1;j+2<n;j++){
                for(int k=j+1;k+1<n;k++){
                    int b=k-arr[i]+arr[j]+arr[k];
                    if(mp[b]){
                        vector<int> v;
                        v.push_back(arr[i]);
                        v.push_back(arr[j]);
                        v.push_back(arr[k]);
                        v.push_back(b);
                        st.insert(v);
                    }
                }
            }
            mp[arr[i]]++;
        }
        for(auto it: st)
            ans.push_back(it);
        
        return ans;
    }
```
why is this giving seg fault?
0
peehugandhi2 weeks ago
it is giving wrong output
 vector<vector<int> > fourSum(vector<int> &arr, int k) 
{
       sort(arr.begin(),arr.end());
       set<vector<int>> st;
       vector<vector<int>> ans;
       for(int i=0;i<arr.size()-3;i++)
       {
         int prevtar=k-arr[i];
           //find-=arr[i];
           for(int j=i+1;j<arr.size()-2;j++)
           {
             int target=prevtar-arr[j];
               //find-=arr[j];
               int k=j+1;
               
               int l=arr.size()-1;
               while(k<l)
               {
                 int cs=arr[k]+arr[l] ;
                   if(arr[k]+arr[l] == target)
                   {
                       vector<int> v;
                       v.push_back(arr[i]);
                       v.push_back(arr[j]);
                       v.push_back(arr[k]);
                       v.push_back(arr[l]);
                       st.insert(v);
                       break;
                   }
                   else if(arr[k] + arr[l] < target)
                   {
                       k++;
                   }
                   else l--;
               }
           }
       }
       for(auto it:st)
       {
           ans.push_back(it);
       }
   r
0
putyavka2 weeks ago
Mapping used.
class Solution{   public:   vector<vector<int> > fourSum(vector<int> &arr, int k) {       const int MIN = -100;       const int MAX = 100;       int N = arr.size();       sort(arr.begin(), arr.end());       vector<int> map(MAX - MIN + 1, -1);       for (int i = 0; i < N; i++)           map[arr[i] - MIN] = i;       vector<vector<int>> res;       for (int i = 0; i < N - 3; i++) {           int arr_i = arr[i];           for (int j = i + 1; j < N - 2; j++) {               int arr_j = arr[j];               for (int m = j + 1; m < N - 1; m++) {                   int arr_m = arr[m];                   int v = k - (arr_i + arr_j + arr_m);                   if (v < MIN || v > MAX) continue;                   int n = map[v - MIN];                   if (n > m) {                       vector<int> q = {arr_i, arr_j, arr_m, arr[n]};                       if (!res.size() || res[res.size() - 1] < q)                           res.push_back(q);                   }               }           }       }       return res;   }};
+2
sachinupreti1902 weeks ago
Happy to share this, As i made this correct in first attempt, Instead of I am beginner in Competitive programming.
 
 
class Solution{   public:   // arr[] : int input array of integers   // k : the quadruple sum required   vector<vector<int> > fourSum(vector<int> &arr, int k) {       // Your code goes here              vector<vector<int>>vec;       vector<int>v;       int i,b,s,j,l;       unordered_map<int,int>m1;       // for(i=0;i<arr.size();i++)       // m1[arr[i]]++;       for(i=0;i<arr.size();i++)       {           for(j=i+1;j<arr.size();j++)           {               for(l=j+1;l<arr.size();l++)               {                   b=k-(arr[i]+arr[j]+arr[l]);                   if(m1[b])                   {                       v.push_back(arr[i]);                       v.push_back(arr[j]);                       v.push_back(arr[l]);                       v.push_back(b);                      // v.push_back($);                       sort(v.begin(),v.end());                       vec.push_back(v);                       v.clear();                   }                                  }                          }           m1[arr[i]]++;       }       vector<vector<int>>fin;       set<vector<int>>se;       for(i=0;i<vec.size();i++)       {           se.insert(vec[i]);       }        set<vector<int>>::iterator it;        for(it=se.begin();it!=se.end();++it)        {            fin.push_back(*it);        }       return fin;          }   };
 
0
divyagupta92 weeks ago
Simple Java Solution with time complexity : O(n3) 
public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) {       int l, r;       int n = arr.length;       Arrays.sort(arr);              ArrayList<ArrayList<Integer>> ans = new ArrayList<>();       HashSet<ArrayList<Integer>> set = new HashSet<>();       if(n<4){           return ans;       }       for(int i=0;i<n-3;i++){           for(int j=i+1;j<n-2;j++){               l = j+1;               r = n-1;               while(l<r){                   if(arr[i]+arr[j]+arr[l]+arr[r]==k){                       ArrayList<Integer> list = new ArrayList<>();                       list.add(arr[i]);                       list.add(arr[j]);                       list.add(arr[l]);                       list.add(arr[r]);                       if(!set.contains(list)){                           ans.add(list);                           set.add(list);                       }                       l++;                       r--;                   }else if(arr[i]+arr[j]+arr[l]+arr[r]<k){                       l++;                   }else{                       r--;                   }               }           }       }       return ans;   }
0
joyrockok3 weeks ago
class Solution {   public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) {       // code here         int N = arr.length;                  Arrays.sort(arr);  ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); HashSet<ArrayList<Integer>> subResult = new HashSet<ArrayList<Integer>>();  ArrayList<Integer> sortList;   for(int i=0; i<N-3; i++) {  for(int j=i+1; j<N-2; j++) {   for(int p=j+1; p<N-1; p++) {    for(int r=p+1; r<N; r++) {          if(arr[i] + arr[j] + arr[p] + arr[r] == k) {      sortList = new ArrayList<Integer>();            sortList.add(arr[i]);      sortList.add(arr[j]);      sortList.add(arr[p]);      sortList.add(arr[r]);           // Collections.sort(sortList);            int size = subResult.size();            subResult.add(sortList);            if(size != subResult.size()) {       resultList.add(sortList);      }     }    }   }  } }  return resultList;   }}
0
chintankothari20003 weeks ago
 vector<vector<int> > fourSum(vector<int> &arr, int k) {
        // Your code goes here
        vector<vector<int> > ans;
        int n=arr.size();
        sort(begin(arr),end(arr));
        for(int i=0;(i+3)<n;i++){
            for(int j=i+1;(j+2)<n;j++){
                int target=k-arr[i]-arr[j];
                int k=j+1,l=n-1;
                while(k<l){
                    int sum=arr[k]+arr[l];
                    if(target==sum){
                        ans.push_back({arr[i],arr[j],arr[k],arr[l]});
                        k++,l--;
                        while(arr[k]==arr[k-1] and arr[l+1]==arr[l])
                            k++,l--;
                    }
                    else if(sum>target)
                        l--;
                    else
                        k++;
                }
                while(j+1<n and arr[j]==arr[j+1])
                    j++;
            }
            while(i+1<n and arr[i]==arr[i+1])
                i++;
        }
        return ans;
    }
0
jayesh293 weeks ago
Easy Java solution
    public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int key) {
        ArrayList<ArrayList<Integer>> al = new ArrayList<>();
        int n=arr.length;
        if(arr==null || n==0)  return al;
        Arrays.sort(arr);
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                int sum_i_j = key-arr[j]-arr[i];
                int lo = j+1, hi= n-1;
                while(lo<hi){
                    int temp_sum = arr[lo]+arr[hi];
                    if(temp_sum<sum_i_j) lo++;
                    else if(temp_sum>sum_i_j)   hi--;
                    else{
                        ArrayList<Integer> sub = new ArrayList<>();
                        sub.add(arr[i]);
                        sub.add(arr[j]);
                        sub.add(arr[lo]);
                        sub.add(arr[hi]);
                        al.add(sub);
                        
                        while(lo<hi && arr[lo]==sub.get(2)) ++lo;
                        while(lo<hi && arr[hi]==sub.get(3)) --hi;
                    }
                }
                while(j+1<n && arr[j+1]==arr[j]) ++j;
            }
            while(i+1<n && arr[i+1]==arr[i]) ++i;
        }
        return al;
    }
0
rohitsingh0000653 weeks ago
GENERIC SOLUTION FOR ALL USING KSUM

class Solution {
    public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) {
        Arrays.sort(arr);
        return solve(arr, k, 0, 4);
    }
    
    private ArrayList<ArrayList<Integer>> solve(int[] arr, int target, int start, int k){
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        int n = arr.length;
        int avg = target/k;
        
        if(k <= 0 || start >= n || arr[start] > avg || avg > arr[n-1])
            return ans;
        if(k == 2){
            return twoSum(arr, target, start);
        }
        
        for(int i = start; i < n; i++){
            if(i == start || arr[i] != arr[i-1]){
                ArrayList<ArrayList<Integer>> subList = solve(arr, target-arr[i], i+1, k-1);
                for(ArrayList<Integer> list : subList){
                    list.add(0, arr[i]);
                    ans.add(list);
                }
            }
        }
        return ans;
    }
    
    private ArrayList<ArrayList<Integer>> twoSum(int[] nums, int target, int start){
        ArrayList<ArrayList<Integer>> results = new ArrayList<>();
        int n = nums.length;
        int lo = start, hi = n - 1;
        
        while (lo < hi) {
            int currSum = nums[lo] + nums[hi];
            if (currSum < target || (lo > start && nums[lo] == nums[lo - 1])) {
                lo++;
            } else if (currSum > target || (hi < n - 1 && nums[hi] == nums[hi + 1])) {
                hi--;
            } else {
                results.add(new ArrayList<>(Arrays.asList(nums[lo ++], nums[hi --])));
            }
        }
        return results;
    }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.