Remove Duplicates and Keep Order

easy Java Collections

Problem

Print the array without repeated values. Keep the first appearance of each value and keep the original order.

Constraints

  • 1 <= n <= 10^5

Examples

Input

6
4 1 4 2 1 3

Output

4 1 2 3

Solutions

Best approachTime O(n)Space O(n)

A normal HashSet loses the order. LinkedHashSet (Java), Set (JavaScript) and dict (Python) keep it.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The array without duplicates.
 * Approach: Use an ordered set.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(int[] a) {
        // Step 1: LinkedHashSet removes duplicates and remembers the insertion order.
        java.util.LinkedHashSet<Integer> seen = new java.util.LinkedHashSet<>();
        for (int value : a) {
            seen.add(value);
        }

        // Step 2: Copy the set into an int array.
        int[] result = new int[seen.size()];
        int index = 0;
        for (int value : seen) {
            result[index++] = value;
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. Which set type remembers the order?