713145. Make array elements unique
Medium
Make Array Elements Unique
Summary
Given an array of integers, write a program to make all elements unique by removing duplicates. This problem involves arrays and sorting concepts.
Detailed Explanation
The approach to solve this problem is straightforward: sort the array in ascending order, then iterate through the sorted array and remove any duplicate elements.
Here's the step-by-step breakdown:
- Sort the input array
arrin ascending order using a sorting algorithm (e.g., quicksort or mergesort). - Initialize an empty array
uniqueArrto store unique elements. - Iterate through the sorted
arrarray, and for each element:- Check if the element is already present in
uniqueArr. If it's not, add it touniqueArr.
- Check if the element is already present in
- Return the
uniqueArr.
Here's a diagram illustrating the process:
arr = [1, 2, 3, 2, 4, 5, 6, 7]
|
| Sort in ascending order
v
[1, 2, 2, 3, 4, 5, 6, 7]
|
| Remove duplicates
v
[1, 2, 3, 4, 5, 6, 7]
Time complexity: O(n log n) due to the sorting step. Space complexity: O(n) for storing the unique elements.
Optimized Solutions
Java
import java.util.Arrays;
public class MakeArrayUnique {
public static int[] makeUnique(int[] arr) {
Arrays.sort(arr);
int[] uniqueArr = new int[arr.length];
int j = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] != arr[i + 1]) {
uniqueArr[j++] = arr[i];
}
}
return uniqueArr;
}
}