Interview Question
Java DevelopersCountry: India
Interview Type: Written Test
Create a hash table (if the numbers < N, and N is small use an array). Scan both list, if the number is already in the hash table, remove the number, else add the number in the hash table.
import java.util.ArrayList;
public class Test {
public static ArrayList a1 = new ArrayList();
public static ArrayList a2 = new ArrayList();
public static ArrayList a3 = new ArrayList();
public static ArrayList check(ArrayList arf,ArrayList arl)
{
for(Object i:arf)
{
if(!arl.contains(i))
{
a3.add(i);
}
}
return a3;
}
public static void main(String[] args) {
a1.add(1);a1.add(2);a1.add(3);a1.add(4);a1.add(5);
a2.add(2);a2.add(2);a2.add(3);a2.add(4);a2.add(5);a2.add(6);
check(a1,a2);
check(a2,a1);
System.out.println(a3);
}
}
As sudBisht said.. here's the implementation.
public class NonRepeating {
public static void main(String[] args) {
List<Integer> a = Lists.newArrayList(1,1,1,13,4,6,77,85,43,34,3,3,77,13);
List<Integer> b = Lists.newArrayList(1,1,1,13,41,6,56,85,43,34,3,3,77,13);
Map<Integer, Integer> map = Maps.newHashMap();
prepareMap(a, map);
prepareMap(b, map);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if(entry.getValue() == 1) {
System.out.println(entry.getKey());
}
}
}
private static void prepareMap(List<Integer> a, Map<Integer, Integer> map) {
for (Integer i : a) {
Integer frequency = map.get(i);
if( frequency == null ) {
map.put(i, 1);
}
else {
map.put(i, frequency+1);
}
}
}
}
creat a arrary of integer range ; so your space complexity will be constant and then
time complexity shoul be O(n);
public void printUncommon (List<Integer >L1 ,List<Integer>L2)
{
int[] numInts = new int[Integer.MAX_VALUE];
for(int i=0;i<Integer.MAX_VALUE;i++) numInts =0;
for(int i=0;i<L1.size();i++)numInts[L1.get(i)]++;
for(int i=0;i<L2.size();i++)numInts[L1.get(i)]++;
for(int i=0;i<Integer.MAX_VALUE;i++)
{
if(numInts[i] == 0) System.out.println(i);
}
JAVA
- lakshaman January 24, 2014