Home > database >  Intersection of two sorted arrays in java
Intersection of two sorted arrays in java

Time:08-17

Trying to solve this question Link to question
As I am a beginner at programming I used this approach and I know it is not an optimized solution to the given problem.

import java.util.*;
public class Solution
{
    public static ArrayList<Integer> findArrayIntersection(ArrayList<Integer> arr1, int n, ArrayList<Integer> arr2, int m)
    {
        // Write Your Code Here.
        ArrayList<Integer> ans = new ArrayList<>();
        for(int i=0;i<n;i  )
        {
            for(int j=0;j<m;j  )
            {
                
                if(arr1.get(i).equals(arr2.get(j)))
                {
                    ans.add(arr1.get(i));
                    arr2.add(j,Integer.MIN_VALUE);
                    break;
                }
            }
        }
        return ans;
    }
}

But None of the test cases passed. What could be the problem with this?

CodePudding user response:

I used a different approach to this question after this failed. Using while loop

import java.util.*;
public class Solution
{
    public static ArrayList<Integer> findArrayIntersection(ArrayList<Integer> arr1, int n, ArrayList<Integer> arr2, int m)
    {
        // Write Your Code Here.
        ArrayList<Integer> ans= new ArrayList<>();
        int i=0,j=0;
        while(i<n && j<m)
        {
            if(arr1.get(i).equals(arr2.get(j)))
            {
                ans.add(arr1.get(i));
                i  ;
                j  ;
            }
            else if(arr1.get(i)<arr2.get(j))
            {
                i  ;
            }else{
                j  ;
            }
        }
        return ans;
    }
}

CodePudding user response:

The problem why your solution doesn't work is because you are not replacing the values with Integer.MIN. You are just adding it, if you for example have a list

[1,2,3,4,5]

and you do

add(2, -1)

you will get

[1,2,-1,3,4,5]

All values just move one place up then.

So just adding

arr2.remove(j 1);

right after

arr2.add(j,Integer.MIN_VALUE);

solves that.

Or better yet. Use set instead of add, like

arr2.set(j,Integer.MIN_VALUE);
  • Related