Challenge: First Repeat

Lab Java Intermediate 20 points

Read n visitor names in the order they arrived. Print the number of different visitors, then the first name that came a second time (or No repeats).

Input

First n, then n names (one word each).

Output

Unique: <count>
First repeat: <name or No repeats>

Example

Input

6
asha ravi meera ravi asha ravi

Output

Unique: 3
First repeat: ravi
Sample input available Sample output available
Editor
Java

Hints

set.add(x) returns false if x was already in the set.

Only remember the first repeat you see.

Solution explanation

A HashSet tells us instantly if we've seen a name before, and its size is the number of different names.

Show solution
import java.util.HashSet;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        HashSet<String> seen = new HashSet<>();
        String firstRepeat = null;
        for (int i = 0; i < n; i++) {
            String name = sc.next();
            if (!seen.add(name) && firstRepeat == null) {
                firstRepeat = name;
            }
        }
        System.out.println("Unique: " + seen.size());
        System.out.println("First repeat: " + (firstRepeat == null ? "No repeats" : firstRepeat));
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD