Skip to content

2 POINTER : Intersection Of Sorted Arrays #67

Description

@SharedMocha

//https://www.interviewbit.com/problems/intersection-of-sorted-arrays/
//Tricks
//USE 2 POINTERS - ONE ON ARRAY A and ONE ON ARRAY B
//IF element if a is euqal to B then add to new array
//Dont worry about For leftovers
//VV IMP while(PA < A.size()-1 || PB < B.size()-1) // dont use <= as this will give array index error
//Time Complexity (M+N)

import java.util.*;
public class HelloWorld{

 public static void main(String []args){
System.out.println("Hello World");
ArrayList<Integer> A = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6));
ArrayList<Integer> B = new ArrayList<Integer>(Arrays.asList(3,5));
ArrayList<Integer> C = new ArrayList<Integer>();
int PA =0;
int PB =0;
while(PA < A.size()-1 || PB < B.size()-1){
if(PA == A.size() || PB == B.size()){
break;
}
if(A.get(PA) == B.get(PB)){
C.add(A.get(PA));
PB++;
}else{
PA++;
}
}
System.out.println(C);
/*
while(PB <= B.size()-1){
A.add(B.get(PB));
PB++;
}*
System.out.println(A);
*/
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions