703399. Remove Duplicates from unsorted array
Basic
Remove Duplicates from Unsorted Array
Summary
The problem requires us to remove duplicates from an unsorted array. This is a basic algorithmic problem that involves iterating over the array and keeping track of unique elements.
Detailed Explanation
To solve this problem, we can use a simple approach: iterate through the array, keep track of the last seen element, and only add elements to our result if they are different from the last seen one. This approach ensures that we do not include duplicate elements in the final result.
Here is a step-by-step breakdown of the solution:
- Initialize an empty list or array to store the unique elements.
- Iterate through the input array, and for each element:
- Check if the current element is different from the last seen element (if we have seen any elements before).
- If it is different, add it to our result list or array.
- Return the final result list or array.
This approach has a time complexity of O(n), where n is the size of the input array, and a space complexity of O(n) as well, since in the worst case we might need to store all elements in the result.
Optimized Solutions
Java
public int[] removeDuplicates(int[] arr) {
if (arr.length == 0) return arr;
int lastSeen = arr[0];
List<Integer> result = new ArrayList<>();
result.add(lastSeen);
for (int i = 1; i < arr.length; i++) {
if (arr[i] != lastSeen) {
lastSeen = arr[i];
result.add(arr[i]);
}
}
int[] uniqueArray = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
uniqueArray[i] = result.get(i);
}
return uniqueArray;
}