How to find all unique triplets that adds up to sum Zero using C#?

CsharpServer Side ProgrammingProgramming

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

Time Complexity − O(n3)

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(n2)

Space Complexity − O(n)

Example

public class Arrays{
   public List<List<int>> ThreeSum(int[] nums){
      List<List<int>> res = new List<List<int>>();
      if (nums == null || nums.Length == 0){
         return res;
      }
      var newnums = nums.OrderBy(x => x).ToArray();
      for (int i = 0; i < newnums.Count(); i++){
         int left = i + 1;
         int right = newnums.Count() - 1;
         while (left < right){
            int sum = newnums[i] + newnums[left] + newnums[right];
            if (sum == 0){
               List<int> l = new List<int>();
               l.Add(newnums[i]);
               l.Add(newnums[left]);
               l.Add(newnums[right]);
               res.Add(l);
               int leftValue = newnums[left];
               while (left < newnums.Length && leftValue == newnums[left]){
                left++;
               }
               int riightValue = newnums[right];
               while (right > left && riightValue == newnums[right]){
                  right--;
               }
            }
            else if (sum < 0){
               left++;
            }
            else{
               right--;
            }
         }
         while (i + 1 < newnums.Length && newnums[i] == newnums[i + 1]){
            i++;
         }
      }
      return res;
   }
}

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

Output

[[-1,-1,2],[-1,,0,1]]
raja
Published on 17-Aug-2021 06:58:58
Advertisements