backtobackswe / backtobackswe-feedback

1 stars 0 forks source link

The 3-Sum Problem #7

Closed gh0stl0nely closed 3 years ago

gh0stl0nely commented 3 years ago

Back To Back SWE



Create a bug report to help us improve our content -



Your email registered on BackToBackSWE : khoinguyen19971997@gmail.com



Category of the bug :



Description of the bug : One of the test cases provide very weird result when running on the platform

=> This one: [9,8,7,6,5,4,3,1,-4,-2]

When I run my code on my local machine, it gives the correct result.



Code you used for Submit/Run operation :

class Solution {
  private static Map<Integer,Integer> map = new HashMap();
  private static Set<List<Integer>> result = new HashSet();

    public static List<List<Integer>> threeSum(int[] A) {
      for(int i = 0; i < A.length; i++){
        if(!map.containsKey(A[i])){
          map.put(A[i],i);
        }
      }

      for(int i = 0; i < A.length - 2; i++){
          int currI = A[i];
        for(int j = i + 1; j < A.length; j++){
          int currJ = A[j];
          int complement = 0 - (currI) - (currJ);
          if(isCombinationPossible(complement, i, j)){
            List<Integer> list = groupByDescending(currI, currJ, complement);
            result.add(list);
          }
        }
      }
      // ON^2 ON

      List<List<Integer>> real = new ArrayList();
      for(List<Integer> list : result){
        real.add(list);
      }

      return real;
    }

    private static boolean isCombinationPossible(int complement, int i1, int i2){
      return map.containsKey(complement) && map.get(complement) != i1 && map.get(complement) != i2;
    }

    private static List<Integer> groupByDescending(int num1, int num2, int num3){
      List<Integer> result = new ArrayList();
      int largest = Math.max(num1, Math.max(num2,num3));
      int smallest = Math.min(num1, Math.min(num2,num3));
      int mid = (num1 + num2 + num3) - (largest + smallest);
      result.add(smallest);
      result.add(mid);
      result.add(largest);

      return result;

    }
}



Language used for code : Java



Expected behavior : To generate an array with the correct unique sets of 3 numbers sum to 0.



Screenshots :

image

The same code running on VSCode, with an extra System.out.println within the ending for-loop to print these (which are the expected result like above):

image



Additional context : I recommend to copy and paste and submit my code version into your own platform to figure out as to why the return ArrayList contain numbers that are not even occurred within the input array.