1

I am trying to write a code to find a triplet whose sum is equal to given target, using list of lists but it is throwing error. I tried increasing heap size in IntelliJ as well as Eclipse, but it still throws error. Following is my code:

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

public class TripleSum {

    public List<List<Integer>> findNumbers(int[] nums, int target){
        Arrays.sort(nums);
        List<List<Integer>> al = new ArrayList<List<Integer>>();
        ArrayList<Integer> lst = new ArrayList<>();
        int l, r;
        int n = nums.length;
        for(int i=0; i<n; i++){
            l=i+1;
            r= n-1;
            while(l<r){
                if(nums[i]+nums[l]+nums[r]==target){
                    lst.add(nums[i]);
                //lst.add(l);
                //lst.add(r);
                }

                else if(nums[i]+nums[l]+nums[r]<target)
                    l++;
                else
                    r--;

            }
            al.add(lst);
        }
        return al;
    }

    public static void main(String[] args){
        int[] arr = {12, 3, 4, 1, 6, 9, 6};
        TripleSum ts = new TripleSum();
        System.out.println(ts.findNumbers(arr, 24));
    }
}
2
  • I recommend using variables that you never look at and wonder "what does this variable do?" - it makes it so much easier to debug. Commented Mar 12, 2018 at 15:38
  • are trying to find a single summation of 3 numbers or all possible combination of 3 numbers in the list that sum to your target? Commented Mar 12, 2018 at 15:40

1 Answer 1

1

I haven't ran a debugger, but I suspect your problem is in this code:

        while(l<r){
            if(nums[i]+nums[l]+nums[r]==target){
                lst.add(nums[i]);
            //lst.add(l);
            //lst.add(r);
            }

            else if(nums[i]+nums[l]+nums[r]<target)
                l++;
            else
                r--;

        }

Let us say that l < r is true right now. Now let us also say that nums[i]+nums[l]+nums[r]==target is true - thus we will add nums[i] to the lst variable.

The else blocks are skipped.

Then the loop loops, and the variables haven't changed. You will loop forever. And add forever. Until, of course, you run out of space, where you crash.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.