◻️4Sum (medium)

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

  • 0 <= a, b, c, d < n

  • a, b, c, and d are distinct.

  • nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

Solutions

Normal

Runtime 188 ms Memory 52.30 MB

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int n = nums.size();
        set<vector<int>> st;
        sort(nums.begin(), nums.end());

        for (int i=0; i+3<n; ++i) {
            for (int j=i+1; j+2<n; ++j) {
                int l = j+1;
                int r = n-1;
                while (l < r) {
                    long long sum = static_cast<long long>(nums[i]) + nums[j] + nums[l] + nums[r];
                    if (sum == target) {
                        st.insert({nums[i], nums[j], nums[l++], nums[r--]});
                    } else if (sum < target) {
                        ++l;
                    } else {
                        --r;
                    }
                }
            }
        }
        return vector<vector<int>>(st.begin(), st.end());
    }
};

Optimised

Runtime 29 ms Memory 16.27 MB

Last updated