Union and Intersection
This question was asked in the first coding round on-site.
Give two sorted lists List<Integer> a and List<Integer> b.
Find
the Union of these two lists -> the union list should also be sorted
the Intersection of these two lists -> Intersection list should also be sorted.
public class UnionIntersection { static void Main(String[] args ) { ArrayList<Integer> l1 = new ArrayList<Integer>(); ArrayList<Integer> l2 = new ArrayList<Integer>(); l1.add(1); l1.add(23); l1.add(26); l1.add(40); l1.add(45); l2.add(-1); l2.add(2); l2.add(6); l2.add(26); l2.add(40); l2.add(50); l2.add(75); for(int val: union( l1, l2 ) ) System.out.print( val + " " ); System.out.println(); for(int val: intersect( l1, l2 ) ) System.out.print( val + " " ); } private static ArrayList<Integer> union( ArrayList<Integer> l1, ArrayList<Integer> l2 ) { if ( l1.size() == 0 ) return l2; if ( l2.size() == 0 ) return l1; ArrayList<Integer> op = new ArrayList<Integer>(); int start1 = 0; int start2 = 0; int end1 = l1.size(); int end2 = l2.size(); while ( start1 < end1 && start2 < end2 ) { if (l1.get(start1) <= l2.get(start2)) { op.add(l1.get(start1)); start1++; } else { op.add(l2.get(start2)); start2++; } } if ( start1 == end1 ) { while ( start2 < end2 ) { op.add(l2.get(start2)); start2++; } } if ( start2 == end2 ) { while ( start1 < end1 ) { op.add(l1.get(start1)); start1++; } } return op; } public static ArrayList<Integer> intersect( ArrayList<Integer> l1, ArrayList<Integer> l2 ) { if ( l1.size() == 0 ) return l2; if ( l2.size() == 0 ) return l1; ArrayList<Integer> op = new ArrayList<Integer>(); int start1 = 0; int start2 = 0; int end1 = l1.size(); int end2 = l2.size(); while ( start1 < end1 && start2 < end2 ) { if ( l1.get(start1) == l2.get(start2) ) { op.add(l1.get(start1)); start1++; start2++; } else if ( l1.get(start1) < l2.get(start2) ) { start1++; continue; } else { start2++; } } return op; } }