joshita / dev

Published

- 1 min read

Three sum smaller

img of Three sum smaller

Given an array return count of 3Sum of elements of the array less than target

  1. Approach brute force, n^3 solution
  2. 2 loop solution, and sorting the array(nlogn sorting)
  3. How to get the count of all the triplets ?????? How does sorting help here ? Answer : approach is the same, we need to optimize it for 2 “for” loops and get the count when sum < target but to get the count we can think like : count += (right-left) Why right-left, because we sorted the array, now if we found input[i] + input[j] + input[k] < target that means the index on which j and k sum is calculated are also less and there are more index which is less than that current index

TotalValue

    private int threeSumSmaller(int input[], int target) {
       int count = 0;
       java.util.List<int[]> list = new ArrayList<>();
       Arrays.sort(input);
       for (int i=0; i < input.length - 2; i++){
           int start = i + 1;
           int end  = input.length - 1;
           while (start < end) {
               if(input[i] + input[start] + input[end] < target) {
                   list.add(new int[]{input[i], input[start], input[end]});
                   count += (end-start);
                   start++;
               } else if(input[i] + input[start] + input[end] >= target) {
                     end--;
               } 
           }
       }
       return count;
   }