Find Duplicate Values

easy Arrays

Problem

Print all values that appear more than once, each one time, in ascending order. Print none if there are no duplicates.

Constraints

  • 1 <= n <= 10^5

Examples

Input

8
4 3 2 7 8 2 3 1

Output

2 3

Solutions

Best approachTime O(n log n)Space O(n)

A frequency map gives the answer in one pass. A value is a duplicate when its count is above 1.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The duplicate values.
 * Approach: Count the values.
 * Time    : O(n log n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(int[] a) {
        // Step 1: Count each value in a TreeMap (sorted by key).
        java.util.TreeMap<Integer, Integer> counts = new java.util.TreeMap<>();
        for (int value : a) {
            counts.merge(value, 1, Integer::sum);
        }

        // Step 2: Collect the values with a count above 1.
        StringBuilder text = new StringBuilder();
        for (java.util.Map.Entry<Integer, Integer> entry : counts.entrySet()) {
            if (entry.getValue() > 1) {
                text.append(text.length() == 0 ? "" : " ").append(entry.getKey());
            }
        }
        return text.length() == 0 ? "none" : text.toString();
    }

    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(solve(a));
    }
}
Hints (1)
  1. How many times must a value appear to be a duplicate?