#C3709. Find Elements Appearing Exactly Twice
Find Elements Appearing Exactly Twice
Find Elements Appearing Exactly Twice
You are given an array of integers where each integer is between 1 and N (inclusive). Your task is to find all the elements that appear exactly twice in the array. If no element appears exactly twice, output -1. Note that if an element appears more than twice, it should not be included in the output.
The order of the output must correspond to the order in which the second occurrence of the element appears in the array.
For example:
- For the array [4, 3, 2, 7, 8, 2, 3, 1], the output is
2 3
because the second occurrence of 2 appears before that of 3. - For the array [1, 1, 2, 2, 3, 3], the output is
1 2 3
. - For the arrays [1, 2, 3, 4, 5] or [1], the output is
-1
.
The underlying idea is to capture the moment when the count of an element becomes exactly 2. If its count becomes 3 or more, it should be removed from the answer since it no longer meets the criterion of appearing exactly twice.
The problem can be formally described by the following condition in LaTeX:
$$\text{Output all } x \text{ such that } \#\{i: arr[i]=x\} = 2, $$or output (-1) if no such element exists.
inputFormat
Input is read from standard input (stdin). The first line contains an integer (T), the number of test cases. For each test case, the first line contains an integer (N), the number of elements in the array. The second line contains (N) space-separated integers representing the array.
outputFormat
For each test case, print a single line to standard output (stdout) containing the elements that appear exactly twice, in the order of their second occurrence, separated by a single space. If no such element exists for a test case, print (-1).## sample
1
8
4 3 2 7 8 2 3 1
2 3
</p>