700258. Remove duplicates in array
Remove Duplicates in Array
Slug: remove-duplicates-in-small-prime-array
Difficulty: Easy
Id: 700258
Topic Tags: Arrays, Hash, Prime Number, Data Structures
Company Tags: Amazon
Summary
Given a small prime array of integers, the problem is to remove duplicates from the array and return the unique elements. This can be achieved by using a hash set or an unordered set in programming.
Detailed Explanation
To solve this problem, we need to iterate through the array once and store each element in a set. Since sets automatically eliminate duplicate values, the resulting set will contain only unique elements from the original array. We then convert the set back into an array (or list) to return as the result.
Here is a step-by-step breakdown of the solution:
- Create an empty set.
- Iterate through the array and for each element:
- Check if the element is already in the set.
- If not, add the element to the set.
- Convert the set back into an array (or list).
- Return the resulting array.
The time complexity of this solution is O(n), where n is the size of the input array. This is because we are iterating through the array once and performing constant-time operations for each element. The space complexity is also O(n) as in the worst case, all elements could be unique and stored in the set.
Here's an example ASCII art diagram to illustrate the solution:
+---------------+
| Input Array |
+---------------+
|
v
+---------------+
| Set |
| (empty initially)|
+---------------+
|
v
+---------------+
| Resulting |
| Array (unique) |
+---------------+
Optimized Solutions
Java
import java.util.*;
public class Main {
public static int[] removeDuplicates(int[] arr) {
Set<Integer> set = new HashSet<>();
for (int num : arr) {
set.add(num);
}
return set.stream().mapToInt(i -> i).toArray();
}
}