Question from GFG

Question


vector<vector<int> > fourSum(vector<int> &arr, int k) {
    // Your code goes here
    set<vector<int>> st;
    sort(arr.begin(), arr.end());
    int n = arr.size();
    for(int i=0; i<n-1; i++){
        for(int j=i+1; j<n; j++){
            int res = k-(arr[i]+arr[j]);
            if(res > 0){
                int x=0; int y=n-1;
                while(y>x){
                    if(arr[y]+arr[x] == res){
                        if(y!=i && y!=j && x!=i && x!=j){
                            vector<int> pre = {arr[i], arr[j], arr[x], arr[y]};
                            sort(pre.begin(), pre.end());
                            st.insert(pre);
                        }
                        y--; x++;
                    }else if(arr[x]+arr[y]>res){
                        y--;
                    }else{
                        x++;
                    }
                }
            }
        }
    }
    vector<vector<int>> ans;
    for(auto it = st.begin(); it != st.end(); it++){
        ans.push_back(*it);
    }
    return ans;
}

I am getting wrong on this test case.

64 -151
56 -52 -14 98 52 77 -39 61 49 -43 2 97 -55 77 -69 84 95 -52 15 -8 73 65 -5 -77 -35 -75 64 26 -28 48 -62 -6 -94 31 91 -40 -88 -12 -28 4 16 35 -14 4 57 -70 -84 -4 -33 -69 97 71 -6 30 -65 -41 -45 -24 10 36 38 45 78 43

Tried many things, but didn’t work. Can someone figure out what I am doing wrong in this.

TRY small testcases for example
0 0 0 0
0
Your output - no output
correct output - 0,0,0,0

1 Like

Thanks I got my mistake

Actually I was putting the following condition

if(res>0)