3866. First Unique Even Element
Description
You are given an integer array nums.
Return an integer denoting the first even integer (earliest by array index) that appears exactly once in nums. If no such integer exists, return -1.
An integer x is considered even if it is divisible by 2.
Β
Example 1:
Input: nums = [3,4,2,5,4,6]
Output: 2
Explanation:
Both 2 and 6 are even and they appear exactly once. Since 2 occurs first in the array, the answer is 2.
Example 2:
Input: nums = [4,4]
Output: -1
Explanation:
No even integer appears exactly once, so return -1.
Β
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solutions
Solution 1: Counting
We can use a hash table or array \(\textit{cnt}\) to count the number of occurrences of each integer in the array. Then we traverse the array again to find and return the first even number that satisfies the condition. If no such even number exists, we return -1.
The time complexity is \(O(n)\), where \(n\) is the length of the array. The space complexity is \(O(M)\), where \(M\) is the range of integers in the array (100 in this problem).
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |