ThreeSum Solution in Java

ThreeSum in java.



Given an array nums of n integers , are there elements a , b , c in nums such that
a + b + c = 0 
Find all unique triplets in the array which gives the sum of zero. Note the solution set must not contain duplicate triplets. Example :
Given array nums = [ -1 , 0 , 1 , 2 ,  -1 ,  -4 ]
A solution set is :

[
    [-1 , 0 , 1],
    [ -1, -1, 2],
]	

  import java.util.*;
  class ThreeSum
  {
      static List<List<Integer>> calculate(int[] arr)
      {
          if(arr == null || arr.length < 3)
          {
              return Collections.emptyList();
          }
          int n = arr.length;
          List<List<Integer>> list = new ArrayList<List<Integer>>();
          Map<Integer,Integer> map = new HashMap<>();

          for(int i=0;i<n-2;i++) {
              int first = arr[i];
              for(int j=i+1;j<n;j++) {
                  int remain = first+arr[j];
                  remain = (remain<0)?Math.abs(remain):(-remain);
                  if(map.containsKey(remain)) {
                      list.add(Arrays.asList(first,remain,arr[j]));
                      map.clear();
                  }
                  map.put(remain,j);
              }
          }
          return list;
      }
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
      try
      {
          int n = input.nextInt();
          // target is 0 
          int[] arr = new int[n];
          for(int i=0;i<n;i++)
              arr[i] = input.nextInt();
          List<List<Integer>> ans = calculate(arr);
          System.out.println(ans);
      }
      catch(Exception e){
        return;
      }
    }
  }

Output :

  6
  -1 0 1 2 -1 -4
  [[0, -1, 1], [2, -1, -1]]

Popular Posts

Family Tree Project in Java

java:17: error: local variables referenced from a lambda expression must be final or effectively final count ++ ;

Creating basic tic tac toe android app using java