Problem Statement
Write a function that removes duplicates from an array and returns a new array with unique elements only.
Examples
Input: [1, 2, 3, 4, 5]
Output: [1, 2, 3, 4, 5]
Input: [1, 2, 2, 3, 4, 4, 5]
Output: [1, 2, 3, 4, 5]
Input: [1, 1, 1, 1, 1]
Output: [1]
Input: []
Output: []
Approach
- Create an empty array to store unique elements.
- Iterate through the input array.
- Check if the current element is already in the unique array.
- If it is not, add it to the unique array.
- Return the unique array.
Code
- We use the spread operator
...
to convert the Set
back to an array.
- This approach ensures that all duplicate elements are removed.
Time Complexity
The time complexity of this solution is O(n), where n is the number of elements in the input array. This is because we need to iterate through the array to check if the current element is already in the unique array.
Space Complexity
The space complexity of this solution is O(n), where n is the number of elements in the input array. This is because we need to store the unique elements in a new array.
Conclusion
The solution is efficient and straightforward, leveraging the Set
object to remove duplicates. This approach ensures that all duplicate elements are removed, and the resulting array contains only unique elements.