I was asked about this during an interview, given a list of numbers, return only the duplicates present in the input as sorted output.
Example:
Input = [6, 7, 5, 6, 1, 0, 1, 0, 5, 3, 2]
Output = [0, 1, 5, 6] - sorted unique numbers which are duplicates in input
I have come up with the below solution:
Approach1:
public static List<Integer> process(List<Integer> input) {
List<Integer> result = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int val : input) {
map.put(val, map.getOrDefault(val, 0) + 1);
}
map.forEach((key, val) -> {
if (val > 1) {
result.add(key);
}
});
result.sort(null);
return result;
}
Updated Approach2:
public static List<Integer> process1(List<Integer> input) {
Set<Integer> dups = new HashSet<>();
Set<Integer> set = new HashSet<>();
for (int val : input) {
if (set.contains(val)) {
dups.add(val);
} else {
set.add(val);
}
}
List<Integer> result = new ArrayList<>(dups);
result.sort(null);
return result;
}
Old Approach2
public static List<Integer> process1(List<Integer> input) {
List<Integer> result = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int val : input) {
if (set.contains(val)) {
result.add(val);
} else {
set.add(val);
}
}
result.sort(null);
return result;
}
Approach1 time complexity is (n)Log(n) as sorting in java is nlogn, space complexity is n
Approach2 time complexity is (n)Log(n) again as sorting in java is nlogn, space complexity is little less as compared to Approach 1, as I hold elements only once in my set.
Please correct me if I am wrong in finding out time and space complexities.
Now the question is whether this logic works if the input contains million of numbers or not? Whether HashMap works if input is million of numbers?
As per my understanding generally, the time complexity for map or set is less, also HashSet internal implementation uses HashMap. How to answer this question.