How to find all the unique quadruplets that is close to zero using C#?

CsharpServer Side ProgrammingProgramming

The easy approach is that we could create four nested loops and check one by one that the sum of all the four elements is zero or not. If the sum of the four elements is zero then print elements.

Time Complexity − O(n4)

Space Complexity − O(1)

We could use an unordered set data structure to store each value of the array. Set provides the benefit of searching an element in O(1) time. So, for each pair in the array, we will look for the negative of their sum that might exist in the set. If such an element is found then we could print the triplet which will be the pair of integers and the negative value of their sum.

Time Complexity − O(n3)

Space Complexity − O(n)

Example

public class Arrays{
   public List<List<int>> FourSum(int[] nums){
      List<List<int>> res = new List<List<int>>();
      if (nums == null || nums.Length == 0){
         return null;
      }
      int[] newNums = nums.OrderBy(x => x).ToArray();
      for (int i = 0; i < newNums.Length; i++){
         for (int j = i; j < newNums.Length; j++){
            int left = j + 1;
            int right = newNums.Length - 1;
            while (left < right){
               int sum = newNums[i] + newNums[j] + newNums[left] + newNums[right];
               if (sum == 0){
                  List<int> sums = new List<int>();
                  sums.Add(newNums[i]);
                  sums.Add(newNums[j]);
                  sums.Add(newNums[left]);
                  sums.Add(newNums[right]);
                  res.Add(sums);
                  int leftValue = newNums[left];
                  int rightValue = newNums[right];
                  while (left < nums.Length && leftValue == nums[left]){
                     left++;
                  }
                  while (right > left && right == nums[right]){
                     right--;
                  }
               }
               else if (sum < 0){
                  left++;
               }
               else{
                  right--;
               }
            }
            while (j + 1 < nums.Length && nums[j] == nums[j + 1]){
               j++;
            }
         }
         while (i + 1 < nums.Length && nums[i] == nums[i + 1]){
            i++;
         }
      }
      return res;
   }
}

static void Main(string[] args){
   Arrays s = new Arrays();
   int[] nums = { 1,0,-1,0,-2,2 };
   var ss = FourSum(nums);
   foreach (var item in ss){
      foreach (var item1 in item){
         Console.WriteLine(item1);
      }
   }
}

Output

[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
raja
Published on 17-Aug-2021 07:36:33
Advertisements