← Arrays

Intersection of Two Arrays

Easy
Python
def intersection(a,b):
    return list(set(a)&set(b))
Java
public int[] intersection(int[] a,int[] b){
    Set<Integer> s=new HashSet<>();
    for(int x:a) s.add(x);
    Set<Integer> r=new HashSet<>();
    for(int x:b) if(s.contains(x)) r.add(x);
    return r.stream().mapToInt(n->n).toArray();
}

Key Insight

Python & operator one expression. Java needs loops and Stream.

Python → Java Differences

  • & operator for intersection
  • Java needs explicit loops
  • Stream for Set to int[] conversion
Python
def intersection(a,b):
    return list(set(a)&set(b))
Java
public int[] intersection(int[] a,int[] b){
    Set<Integer> s=new HashSet<>();
    for(int x:a) s.add(x);
    Set<Integer> r=new HashSet<>();
    for(int x:b) if(s.contains(x)) r.add(x);
    return r.stream().mapToInt(n->n).toArray();
}

Algorithm Steps

1. Convert to sets
2. Intersect