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:

  1. Sort the input array arr in ascending order using a sorting algorithm (e.g., quicksort or mergesort).
  2. Initialize an empty array uniqueArr to store unique elements.
  3. Iterate through the sorted arr array, and for each element:
    • Check if the element is already present in uniqueArr. If it's not, add it to uniqueArr.
  4. 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

View on GeeksforGeeks
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;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.