2

This is my code of finding common elements from three arrays. I am trying to add the elements in the ArrayList by using add() function but I am getting this out of memory error. This is my code-

ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2, int n3) 
{
    // code here
    ArrayList<Integer> ls=new ArrayList<Integer>(n1);
    int i=0,j=0,k=0;
    while(i<n1 && j<n2 && k<n3){
        if(A[i]==B[j] && B[j]==C[k]){
            int t=A[i];
            ls.add(t);
        }else if(A[i]<B[j]){
            i++;
        }else if(B[j]<C[k]){
            j++;
        }else{
            k++;
        }
    }
    return ls;
}

this is my error-

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.Arrays.copyOf(Arrays.java:3720)
at java.base/java.util.Arrays.copyOf(Arrays.java:3689)
at java.base/java.util.ArrayList.grow(ArrayList.java:237)
at java.base/java.util.ArrayList.grow(ArrayList.java:242)
at java.base/java.util.ArrayList.add(ArrayList.java:485)
at java.base/java.util.ArrayList.add(ArrayList.java:498)
at Solution.commonElements(GFG.java:68)
at GFG.main(GFG.java:36)
  • Step through your code with the debugger and you'll see what's wrong. In the case in which you add an item to the list, which loop index variables get incremented? – tgdavies Oct 08 '21 at 04:46
  • When all elements are equal, you add it to the output and iterate again. Since you don’t change i, j or k the elements are still the same and you add the same element again. And again. – Joachim Isaksson Oct 08 '21 at 05:10

3 Answers3

0
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space 

Java is saying it ran out of memory. There is an endless loop that causes the condition to never exit while loop, endlessly incrementing one of the variables until memory cap has been reached. Review the conditions of while flow control.

Borel
  • 29
  • 4
0

When the common elements are being found i.e

if(A[i]==B[j] && B[j]==C[k]){ int t=A[i]; ls.add(t); }

You haven't incremented either i or j or k, hence it is getting stuck in an infinite loop leading to the heap space usage. Incrementing them should do the job ideally.

0

I needed to increment of i,j,k in my if condition to prevent it from this error.

ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2, int n3) 
{
    // code here
    ArrayList<Integer> ls=new ArrayList<Integer>(n1);
    int i=0,j=0,k=0;
    while(i<n1 && j<n2 && k<n3){
        if(A[i]==B[j] && B[j]==C[k]){
            if(!ls.contains(A[i])){
                ls.add(A[i]);
            }
            i++;
            j++;
            k++;
        }else if(A[i]<B[j]){
            i++;
        }else if(B[j]<C[k]){
            j++;
        }else{
            k++;
        }
    }
    return ls;
}