4Sum Ld Pgamming Sluins | Ld Pblm Sluins in ++, Java, & Pyhn []

4Sum LeetCode Problem | LeetCode Problems For Beginners | LeetCode Problems & Solutions | Improve Problem Solving Skills | LeetCode Problems Java | LeetCode Problems C++

Hello Programmers/Coders, Today we are going to share solutions to the Programming problems of LeetCode Solutions in C++, Java, & Python. At Each Problem with Successful submission with all Test Cases Passed, you will get a score or marks and LeetCode Coins. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for the 4Sum in C++, Java & Python-LeetCode problem. We are providing the correct and tested solutions to coding problems present on LeetCode. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

About LeetCode

LeetCode is one of the most well-known online judge platforms to help you enhance your skills, expand your knowledge and prepare for technical interviews. 

LeetCode is for software engineers who are looking to practice technical questions and advance their skills. Mastering the questions in each level on LeetCode is a good way to prepare for technical interviews and keep your skills sharp. They also have a repository of solutions with the reasoning behind each step.

LeetCode has over 1,900 questions for you to practice, covering many different programming concepts. Every coding problem has a classification of either EasyMedium, or Hard.

LeetCode problems focus on algorithms and data structures. Here is some topic you can find problems on LeetCode:

  • Mathematics/Basic Logical Based Questions
  • Arrays
  • Strings
  • Hash Table
  • Dynamic Programming
  • Stack & Queue
  • Trees & Graphs
  • Greedy Algorithms
  • Breadth-First Search
  • Depth-First Search
  • Sorting & Searching
  • BST (Binary Search Tree)
  • Database
  • Linked List
  • Recursion, etc.

Leetcode has a huge number of test cases and questions from interviews too like Google, Amazon, Microsoft, Facebook, Adobe, Oracle, Linkedin, Goldman Sachs, etc. LeetCode helps you in getting a job in Top MNCs. To crack FAANG Companies, LeetCode problems can help you in building your logic.

Link for the Problem4Sum– LeetCode Problem

4Sum– LeetCode Problem

Problem:

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
  • abc, 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]]

Constraints:

  • 1 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
4Sum– LeetCode Solutions
class Solution {
 public:
  vector> fourSum(vector& nums, int target) {
    vector> ans;
    vector path;

    sort(begin(nums), end(nums));
    nSum(nums, 4, target, 0, nums.size() - 1, path, ans);

    return ans;
  }

 private:
  // in [l, r], find n numbers add up to the target
  void nSum(const vector& nums, int n, int target, int l, int r,
            vector& path, vector>& ans) {
    if (r - l + 1 < n || target < nums[l] * n || target > nums[r] * n)
      return;
    if (n == 2) {
      // very similar to the sub procedure in 15. 3Sum
      while (l < r) {
        const int sum = nums[l] + nums[r];
        if (sum == target) {
          path.push_back(nums[l]);
          path.push_back(nums[r]);
          ans.push_back(path);
          path.pop_back();
          path.pop_back();
          ++l;
          --r;
          while (l < r && nums[l] == nums[l - 1])
            ++l;
          while (l < r && nums[r] == nums[r + 1])
            --r;
        } else if (sum < target) {
          ++l;
        } else {
          --r;
        }
      }
      return;
    }

    for (int i = l; i <= r; ++i) {
      if (i > l && nums[i] == nums[i - 1])
        continue;
      path.push_back(nums[i]);
      nSum(nums, n - 1, target - nums[i], i + 1, r, path, ans);
      path.pop_back();
    }
  }
};
class Solution {
  public List> fourSum(int[] nums, int target) {
    List> ans = new ArrayList<>();

    Arrays.sort(nums);
    nSum(nums, 4, target, 0, nums.length - 1, new ArrayList<>(), ans);

    return ans;
  }

  // in [l, r], find n numbers add up to the target
  private void nSum(int[] nums, int n, int target, int l, int r, List path,
                    List> ans) {
    if (r - l + 1 < n || target < nums[l] * n || target > nums[r] * n)
      return;
    if (n == 2) {
      // very similar to the sub procedure in 15. 3Sum
      while (l < r) {
        final int sum = nums[l] + nums[r];
        if (sum == target) {
          path.add(nums[l]);
          path.add(nums[r]);
          ans.add(new ArrayList<>(path));
          path.remove(path.size() - 1);
          path.remove(path.size() - 1);
          ++l;
          --r;
          while (l < r && nums[l] == nums[l - 1])
            ++l;
          while (l < r && nums[r] == nums[r + 1])
            --r;
        } else if (sum < target) {
          ++l;
        } else {
          --r;
        }
      }
      return;
    }

    for (int i = l; i <= r; ++i) {
      if (i > l && nums[i] == nums[i - 1])
        continue;
      path.add(nums[i]);
      nSum(nums, n - 1, target - nums[i], i + 1, r, path, ans);
      path.remove(path.size() - 1);
    }
  }
}
class Solution:
  def fourSum(self, nums: List[int], target: int):
    def nSum(l: int, r: int, target: int, n: int, path: List[int], ans: List[List[int]]) -> None:
      if r - l + 1 < n or n < 2 or target < nums[l] * n or target > nums[r] * n:
        return
      if n == 2:
        while l < r:
          sum = nums[l] + nums[r]
          if sum == target:
            ans.append(path + [nums[l], nums[r]])
            l += 1
            while nums[l] == nums[l - 1] and l < r:
              l += 1
          elif sum < target:
            l += 1
          else:
            r -= 1
        return

      for i in range(l, r + 1):
        if i > l and nums[i] == nums[i - 1]:
          continue

        nSum(i + 1, r, target - nums[i], n - 1, path + [nums[i]], ans)

    ans = []

    nums.sort()
    nSum(0, len(nums) - 1, target, 4, [], ans)

    return ans

Leave a Comment

Scroll to Top