Find all triplets with zero sum

0

 

All triplets with zero sum refers to a group of three numbers in an array or a collection of numbers where the sum of those three numbers is zero.

For example,

Input :

arr [] = [0, -1, 2, -3, 1], Output : [0, -1, 1] , [-3, 2, 1]. These triplets are interesting to find because they can provide insights into the relationships between the numbers in the collection and can help solve certain problems.

Here's an example implementation in Java that finds all the unique triplets in an array that have a sum of zero:



import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TripletWithZeroSum {
  public static void main(String[] args) {
    int[] arr = {0, -1, 2, -3, 1};
    List<List<Integer>> result = findTriplets(arr);
    System.out.println(result);
  }

  public static List<List<Integer>> findTriplets(int[] arr) {
    List<List<Integer>> result = new ArrayList<>();
    Arrays.sort(arr);

    for (int i = 0; i < arr.length - 2; i++) {
      if (i > 0 && arr[i] == arr[i - 1]) {
        continue;
      }
      int left = i + 1;
      int right = arr.length - 1;

      while (left < right) {
        int sum = arr[i] + arr[left] + arr[right];
        if (sum == 0) {
          result.add(Arrays.asList(arr[i], arr[left], arr[right]));
          while (left < right && arr[left] == arr[left + 1]) {
            left++;
          }
          while (left < right && arr[right] == arr[right - 1]) {
            right--;
          }
          left++;
          right--;
        } else if (sum < 0) {
          left++;
        } else {
          right--;
        }
      }
    }
    return result;
  }
}



This program sorts the input array, then uses two pointers to find the triplets. The left pointer starts from the next element of the current element and the right pointer starts from the end of the array. If the sum of the current element, the left element, and the right element is equal to zero, we add the triplet to the result and move both the left and right pointers inward. If the sum is less than zero, we move the left pointer inward. If the sum is greater than zero, we move the right pointer inward.



Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !