Challenge: First Repeat
Completed
Read n numbers in order. Print the first number that appears for a second time (the one whose repeat comes earliest). If nothing repeats, print none.
Input
Line 1: n. Line 2: n whole numbers.
Output
The first repeated number, or none.
Example
Input
7 4 2 7 2 4 9 7
Output
2
Editor
Java
Hints
Walk through the numbers with a HashSet of what you've seen.
seen.add(x) returns false when x was already there.
Solution explanation
One pass with O(1) set lookups: O(n). Read all n numbers before stopping, so no input is left over.
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();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
HashSet<Integer> seen = new HashSet<Integer>();
for (int x : a) {
if (!seen.add(x)) {
System.out.println(x);
return;
}
}
System.out.println("none");
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module