Distinct elements in Unsorted Array

Last Updated : 23 Oct, 2026

Given an array arr[] of integers which may or may not contain duplicate elements. The task is to remove duplicate elements. Your result should have elements according their first appearance in the input array.

Examples: 

Input: arr[] = [1, 2, 3, 1, 4, 2]
Output: [1, 2, 3, 4]
Explanation: 2 and 1 have more than 1 occurrence.

Input: arr[] = [1, 2, 3, 4]
Output: [1, 2, 3, 4]
Explanation: There is no duplicate element.

Try It Yourself
redirect icon

[Naive Approach] Nested loops - O(n ^ 2) Time and O(n) Space

The idea is to use two nested loops.

  • The outer loop picks an element one by one starting from the leftmost element.
  • The inner loop checks if the element is present on left side of it.
  • If present, then ignore the element, else store it in result.
C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> removeDuplicate(vector<int> &arr)
{
    vector<int> res;

    for (int i = 0; i < arr.size(); i++)
    {

        // Check if this element is included in result
        int j;
        for (j = 0; j < i; j++)
            if (arr[i] == arr[j])
                break;

        // Include this element if not included previously
        if (i == j)
            res.push_back(arr[i]);
    }
    return res;
}

int main()
{
    vector<int> arr = {1, 2, 3, 1, 4, 2};

    vector<int> res = removeDuplicate(arr);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        if (i > 0)
            cout << ", ";
        cout << res[i];
    }
    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;

public class GFG {
    public static ArrayList<Integer>
    removeDuplicate(int[] arr)
    {
        ArrayList<Integer> res = new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {

            // Check if this element is included in result
            int j;
            for (j = 0; j < i; j++)
                if (arr[i] == arr[j])
                    break;

            // Include this element if not included
            // previously
            if (i == j)
                res.add(arr[i]);
        }
        return res;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 1, 4, 2 };

        ArrayList<Integer> res = removeDuplicate(arr);

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            if (i > 0)
                System.out.print(", ");
            System.out.print(res.get(i));
        }
        System.out.print("]");
    }
}
Python
def removeDuplicate(arr):
    res = []

    # Traverse the input array
    for i in range(len(arr)):
        found = False

        # Check if the element appeared previously
        for j in range(i):
            if arr[i] == arr[j]:
                found = True
                break

        # Add the element if it is not a duplicate
        if not found:
            res.append(arr[i])

    return res


if __name__ == "__main__":
    arr = [1, 2, 3, 1, 4, 2]
    res = removeDuplicate(arr)

    print("[", end="")
    for i in range(len(res)):
        if i > 0:
            print(", ", end="")
        print(res[i], end="")
    print("]")
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<int> removeDuplicate(int[] arr)
    {
        List<int> res = new List<int>();

        // Traverse the input array
        for (int i = 0; i < arr.Length; i++) {
            bool found = false;

            // Check if the element appeared previously
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    found = true;
                    break;
                }
            }

            // Add the element if it is not a duplicate
            if (!found) {
                res.Add(arr[i]);
            }
        }

        return res;
    }

    static void Main()
    {
        int[] arr = { 1, 2, 3, 1, 4, 2 };
        List<int> res = removeDuplicate(arr);

        // Print the result
        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            if (i > 0)
                Console.Write(", ");
            Console.Write(res[i]);
        }
        Console.Write("]");
    }
}
JavaScript
function removeDuplicate(arr)
{
    let res = [];

    for (let i = 0; i < arr.length; i++) {

        // Check if this element is included in result
        let j;
        for (j = 0; j < i; j++)
            if (arr[i] === arr[j])
                break;

        // Include this element if not included previously
        if (i === j)
            res.push(arr[i]);
    }
    return res;
}

// Driver Code
let arr = [ 1, 2, 3, 1, 4, 2 ] 
let res = removeDuplicate(arr);
console.log(JSON.stringify(res));

Output
[1, 2, 3, 4]

[Expected Approach] Hash Set - O(n) Time and O(n) Space

The idea is to use a hash set to track elements that have already appeared and add only the first occurrence of each element to the result vector.

Working of Approach:

  • Create an empty hash set s to store elements that have already appeared.
  • Create a result vector v to store the unique elements.
  • Traverse the input array from left to right.
  • If the current element is not present in s, insert it into the set and add it to v.
  • Return v after processing all elements.

Let us understand with an example:
Input: arr[] = [1, 2, 3, 1, 4, 2]

  • Initially, s = {} and v = [].
  • For 1, 2, and 3, each element is not present in s, so insert it into s and v. Now, v = [1, 2, 3].
  • For the next 1, it is already present in s, so skip it.
  • For 4, it is not present in s, so insert it into s and v. Now, v = [1, 2, 3, 4].
  • For the last 2, it is already present in s, so skip it and return v.

Output: [1, 2, 3, 4].

C++
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;

vector<int> removeDuplicate(vector<int> &arr)
{
    // Creates an empty hashset
    int n = arr.size();
    unordered_set<int> s;
    vector<int> v;

    // Traverse the input array
    for (int i = 0; i < n; i++)
    {
        // If not present, then put it in
        // hashtable and print it
        if (s.find(arr[i]) == s.end())
        {
            s.insert(arr[i]);
            v.push_back(arr[i]);
        }
    }
    return v;
}

int main()
{
    vector<int> arr = {1, 2, 3, 1, 4, 2};

    vector<int> res = removeDuplicate(arr);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        if (i > 0)
            cout << ", ";
        cout << res[i];
    }
    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.HashSet;

public class GFG {
    public static ArrayList<Integer>
    removeDuplicate(int[] arr)
    {
        // Creates an empty hashset
        int n = arr.length;
        HashSet<Integer> s = new HashSet<>();
        ArrayList<Integer> v = new ArrayList<>();

        // Traverse the input array
        for (int i = 0; i < n; i++) {
            // If not present, then put it in
            // hashtable and print it
            if (!s.contains(arr[i])) {
                s.add(arr[i]);
                v.add(arr[i]);
            }
        }
        return v;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 1, 4, 2 };
        ArrayList<Integer> res = removeDuplicate(arr);
        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            if (i > 0)
                System.out.print(", ");
            System.out.print(res.get(i));
        }
        System.out.print("]");
    }
}
Python
def removeDuplicate(arr):
    # Creates an empty hashset
    n = len(arr)
    s = set()
    v = []

    # Traverse the input array
    for i in range(n):
        # If not present, then put it in
        # hashtable and print it
        if arr[i] not in s:
            s.add(arr[i])
            v.append(arr[i])
    return v

if __name__ == '__main__':
    arr = [1, 2, 3, 1, 4, 2]
    res = removeDuplicate(arr)
    print('[', end='')
    for i in range(len(res)):
        if i > 0:
            print(', ', end='')
        print(res[i], end='')
    print(']')
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<int> removeDuplicate(int[] arr)
    {
        // Creates an empty hashset
        int n = arr.Length;
        HashSet<int> s = new HashSet<int>();
        List<int> v = new List<int>();

        // Traverse the input array
        for (int i = 0; i < n; i++) {

            // If not present, add it to the hashset
            // and result list
            if (!s.Contains(arr[i])) {
                s.Add(arr[i]);
                v.Add(arr[i]);
            }
        }

        return v;
    }

    static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 1, 4, 2 };

        List<int> res = removeDuplicate(arr);

        // Print the result
        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            if (i > 0)
                Console.Write(", ");
            Console.Write(res[i]);
        }
        Console.Write("]");
    }
}
JavaScript
function removeDuplicate(arr)
{
    // Creates an empty hashset
    let n = arr.length;
    let s = new Set();
    let v = [];

    // Traverse the input array
    for (let i = 0; i < n; i++) {
        // If not present, then put it in
        // hashtable and print it
        if (!s.has(arr[i])) {
            s.add(arr[i]);
            v.push(arr[i]);
        }
    }
    return v;
}

// Driver Code
let arr = [ 1, 2, 3, 1, 4, 2 ];
let res = removeDuplicate(arr);
console.log("[" + res.join(", ") + "]");

Output
[1, 2, 3, 4]
Comment