Persistent Systems Interview Question
Java DevelopersCountry: India
Interview Type: Written Test
This code will run in O(n) and space complexity O(k) where K = max(arr1.length, arr2.length)
/**
* Given two char[] arrays of arbitrary length, return the intersection of the arrays
* Example {'p','q','r'} , {'a','b','c', 'p'}
*
* @author Fayez El-Far
*
*/
public class IntersectionOfSets
{
public List<Character> findIntersection(char[] arr1, char[] arr2)
{
if(arr1 == null || arr2 == null) { throw new IllegalArgumentException(); }
if(arr1.length == 0 || arr2.length == 0) { return null;}
HashSet<Character> set = new HashSet<>();
List<Character> intersection = new ArrayList<>();
//Insert the longer of the two arrays while ensuring not to insert repeated elements more than once
if(arr1.length >= arr2.length)
{
for(int i = 0; i < arr1.length; i++)
set.add(arr1[i]);
for(int j = 0; j < arr2.length; j++)
{
if(set.contains(arr2[j]))
{
if(intersection == null) { intersection = new ArrayList<>();}
intersection.add(arr2[j]);
}
}
}
else
{
for(int i = 0; i < arr2.length; i++)
set.add(arr2[i]);
for(int j = 0; j < arr1.length;j++)
{
if(set.contains(arr1[j]))
{
if(intersection == null) { intersection = new ArrayList<>();}
intersection.add(arr1[j]);
}
}
}
return intersection;
}
}
import java.util.regex.*;
import java.util.*;
class Intersection
{
public static void main(String args[])
{
String input[]={"p","q","r"};
String input2[]={"p","s","w"};
for(String str:input)
{
Pattern p=Pattern.compile(str);
for(String str2:input2)
{
Matcher m=p.matcher(str2);
while(m.find())
{
System.out.println(m.group());
}
}
}
}
}
- NoOne October 07, 2016