Showing posts with label interview questions. Show all posts
Showing posts with label interview questions. Show all posts

Monday, October 1, 2018

How to Find Multiple Missing Integers in Given Array With Duplicates in Java?


I found this interesting problem here: 
https://javarevisited.blogspot.com/2014/11/how-to-find-missing-number-on-integer-array-java.html
but I think the solution is too long, see mine below:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class MissingIntegers {

    public static void main(String[] args) {
       
        Set<Integer> s1 = new HashSet<>(Arrays.asList(new Integer[]{1, 2, 3, 4, 9, 8}));
        Set<Integer> s2 = new HashSet<>(IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList()));

        s2.removeAll(s1);
        System.out.println(s2);
    }
   
}


In fact we don't need the intermediate List in the case of Set 2, we can use the toCollection method of Collectors:

Set<Integer> s2 = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toCollection(HashSet::new));

Next day I came up with another solution:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class MissingIntegers {

    public static void main(String[] args) {
       
        List<Integer> L1 = Arrays.asList(new Integer[]{1, 2, 3, 4, 9, 2, 8});
        List<Integer> L2 = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toCollection(ArrayList::new));
       
        L2.removeAll(L1);
        System.out.println(L2);
    }
   
}