3866. First Unique Even Element
Problem 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.
In other words, you need to scan through the array and find the very first number that meets two conditions at the same time:
- It is an even number (i.e.,
x % 2 == 0). - It occurs only once across the entire array.
The "first" here refers to the earliest position by array index. If you find such a number, return its value. If the array contains no even number that appears exactly once, return -1.
How We Pick the Algorithm
Why Hash Table / Counting?
This problem maps to Hash Table / Counting through a short path in the full flowchart.
Two-pass counting: build frequency map, then scan for the first even element with count exactly 1.
Open in FlowchartIntuition
The problem asks us to find the first even number that appears exactly once. There are two pieces of information we care about for each number: whether it is even, and how many times it appears in the array.
Checking whether a number is even is easy β we just test x % 2 == 0. The trickier part is knowing how many times a number occurs. If we tried to count occurrences on the fly while scanning, we would have to look ahead and behind repeatedly, which is wasteful.
A cleaner idea is to separate the work into two passes. In the first pass, we count how many times every number appears and store these counts in a hash table. Once we have all the counts ready, the occurrence information for any number can be looked up instantly.
In the second pass, we walk through the array in its original order. Because we go from left to right, the first number we encounter that satisfies both conditions β being even and having a count of exactly 1 β is guaranteed to be the earliest such number by index, so we return it immediately. If we finish the scan without finding any qualifying number, we return -1.
Solution Approach
Solution 1: Counting
We can use a hash table or array 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 concrete steps are as follows:
-
Build a counter
cntusingCounter(nums). After this step,cnt[x]tells us exactly how many times the valuexappears innums. This takes a single pass over the array. -
Traverse
numsagain from left to right. For each elementx, we check two conditions together:x % 2 == 0, meaningxis even.cnt[x] == 1, meaningxappears exactly once in the whole array.
-
The moment both conditions hold, we have found the earliest qualifying number by index, so we return
xright away. -
If the loop completes without returning, no even number appears exactly once, so we return
-1.
The data structure used here is a hash table (Counter), which gives us O(1) average-time lookups for occurrence counts.
The reference implementation in Python:
class Solution:
def firstUniqueEven(self, nums: list[int]) -> int:
cnt = Counter(nums)
for x in nums:
if x % 2 == 0 and cnt[x] == 1:
return x
return -1
The time complexity is O(n), where n is the length of the array nums, since we make two passes over it. The space complexity is O(n), which is needed for the hash table cnt to store the count of each distinct value.
Example Walkthrough
Let's trace through the solution with the input nums = [4, 2, 4, 6, 3, 2].
Step 1: Build the count table (first pass)
We scan through every element and tally how many times each value appears:
| Value | Count |
|---|---|
4 | 2 |
2 | 2 |
6 | 1 |
3 | 1 |
So cnt = {4: 2, 2: 2, 6: 1, 3: 1}. Now we can look up any value's frequency instantly.
Step 2: Traverse the array again (second pass)
We walk through nums from left to right, checking both conditions β even (x % 2 == 0) and appears exactly once (cnt[x] == 1):
| Index | x | Even? (x % 2 == 0) | Unique? (cnt[x] == 1) | Action |
|---|---|---|---|---|
0 | 4 | β Yes | β No (count is 2) | Skip |
1 | 2 | β Yes | β No (count is 2) | Skip |
2 | 4 | β Yes | β No (count is 2) | Skip |
3 | 6 | β Yes | β
Yes (count is 1) | Return 6 |
At index 3, the value 6 satisfies both conditions: it is even, and it appears exactly once in the array. Since we scan from left to right, this is guaranteed to be the earliest such number, so we return 6 immediately without examining the rest of the array.
Why the order matters: Notice that 3 at index 4 also appears exactly once, but it is odd, so it fails the first condition. And even though 4 and 2 are even and appear earlier, they each occur twice, so they fail the uniqueness check. The two-pass approach lets us confirm uniqueness up front, so the second pass cleanly returns the first valid match by index.
Edge case: If the array were [4, 4, 3, 3], no even number appears exactly once (4 appears twice, 3 is odd), so the loop would finish without returning, and we'd return -1.
Solution Implementation
1from collections import Counter
2from typing import List
3
4
5class Solution:
6 def firstUniqueEven(self, nums: List[int]) -> int:
7 # Count the occurrences of each number in the list
8 count = Counter(nums)
9
10 # Iterate through the numbers in their original order
11 for num in nums:
12 # Return the first number that is even and appears exactly once
13 if num % 2 == 0 and count[num] == 1:
14 return num
15
16 # No qualifying number found
17 return -1
181class Solution {
2 /**
3 * Finds the first even number in the array that appears exactly once.
4 *
5 * @param nums the input array (values assumed to be in range [0, 100])
6 * @return the first unique even number, or -1 if none exists
7 */
8 public int firstUniqueEven(int[] nums) {
9 // Frequency table for values 0..100
10 int[] count = new int[101];
11
12 // First pass: tally the occurrences of each value
13 for (int num : nums) {
14 ++count[num];
15 }
16
17 // Second pass: return the first value that is even and unique
18 for (int num : nums) {
19 if (num % 2 == 0 && count[num] == 1) {
20 return num;
21 }
22 }
23
24 // No qualifying number found
25 return -1;
26 }
27}
281class Solution {
2public:
3 int firstUniqueEven(vector<int>& nums) {
4 // Frequency array; constraint assumes values are in range [0, 100].
5 int count[101]{};
6
7 // First pass: tally how many times each value appears.
8 for (int num : nums) {
9 ++count[num];
10 }
11
12 // Second pass: return the first value that is even and appears exactly once.
13 for (int num : nums) {
14 if (num % 2 == 0 && count[num] == 1) {
15 return num;
16 }
17 }
18
19 // No qualifying element found.
20 return -1;
21 }
22};
231/**
2 * Finds the first even number in the array that appears exactly once.
3 *
4 * Approach:
5 * 1. Count the occurrences of each value using a fixed-size frequency array
6 * (values are assumed to be within the range [0, 100]).
7 * 2. Iterate through the original array in order and return the first value
8 * that is both even and has a frequency of exactly one.
9 *
10 * @param nums - The input array of numbers (each within [0, 100]).
11 * @returns The first unique even number, or -1 if none exists.
12 */
13function firstUniqueEven(nums: number[]): number {
14 // Frequency array to record how many times each value appears.
15 const count: number[] = new Array(101).fill(0);
16
17 // First pass: tally the occurrences of every number.
18 for (const num of nums) {
19 count[num]++;
20 }
21
22 // Second pass: find the first even number that occurs exactly once.
23 for (const num of nums) {
24 if (num % 2 === 0 && count[num] === 1) {
25 return num;
26 }
27 }
28
29 // No unique even number was found.
30 return -1;
31}
32Time and Space Complexity
-
Time Complexity:
O(n), wherenis the length of the arraynums. Building theCounterrequires a single pass over allnelements, takingO(n)time. The subsequentforloop also iterates over the array at most once, performing constant-time operations (the parity checkx % 2 == 0and the dictionary lookupcnt[x]) for each element, contributing anotherO(n). The total time is thereforeO(n). -
Space Complexity:
O(M), whereMis the range of distinct integer values in the array (100 in this problem). TheCounterobject stores one entry per unique value innums, so the extra space scales with the number of distinct integers, which is bounded byM. No other auxiliary data structures grow with the input, hence the space complexity isO(M).
Pattern Learn more about how to find time and space complexity quickly.
Common Pitfalls
Pitfall 1: Misclassifying Negative Even Numbers and Zero
A frequent mistake is assuming the array contains only positive integers and writing an evenness check that breaks for negatives or zero.
- Zero (
0): Zero is even (0 % 2 == 0), so it is a valid candidate. Forgetting this can cause you to incorrectly skip a legitimate answer. - Negative even numbers (e.g.,
-4): In Python,(-4) % 2 == 0works correctly, so the standard checknum % 2 == 0is safe. However, in languages like C++ or Java,%can return a negative remainder (-3 % 2 == -1), so a check likenum % 2 == 1to detect odd numbers would fail for negatives. Always testnum % 2 == 0for evenness, nevernum % 2 == 1for oddness.
Safe approach (language-agnostic):
# Correct: directly test for even if num % 2 == 0: ...
In C++/Java, prefer num % 2 == 0 or use (num & 1) == 0, which correctly identifies even numbers regardless of sign.
Pitfall 2: Counting Parity Instead of Counting the Value
Some implementations mistakenly track how many times an even number appears in aggregate, rather than counting each distinct value. The condition cnt[x] == 1 must refer to the occurrence count of the specific value x, not a collective count of all even numbers.
# Wrong: this counts how many even numbers exist, not occurrences of x
even_count = sum(1 for v in nums if v % 2 == 0)
# Correct: count each distinct value
cnt = Counter(nums)
Pitfall 3: Returning the First Unique Value, Then Filtering for Even
A subtle logic error is finding the first value that appears exactly once and only afterwards checking if it is even. This produces the wrong answer because the first unique value might be odd, while the intended answer is the first unique even value.
# Wrong: finds first unique number, may be odd for num in nums: if cnt[num] == 1: return num if num % 2 == 0 else -1 # bug: bails out too early # Correct: both conditions must hold simultaneously before returning for num in nums: if num % 2 == 0 and cnt[num] == 1: return num
The two conditions must be combined in a single and check so that odd unique numbers are skipped over without terminating the search.
Pitfall 4: Confusing "First by Index" with "First by Value"
The problem asks for the earliest qualifying element by array index, not the smallest qualifying value. Sorting the array or iterating over cnt.keys() (which may not preserve original order in older contexts) breaks this requirement.
# Wrong: iterating over the counter keys loses index order intent for x in cnt: if x % 2 == 0 and cnt[x] == 1: return x # may not be the earliest by index # Correct: iterate over nums to preserve original positional order for num in nums: if num % 2 == 0 and cnt[num] == 1: return num
Always perform the second pass over the original nums array to guarantee positional correctness.
Ready to land your dream job?
Unlock your dream job with a 5-minute quiz for a personalized study roadmap!
Get My RoadmapHow many ways can you arrange the three letters A, B and C?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion If you prefer videos here's a video that explains recursion in a fun and easy way Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask him
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity describes how the time needed
Want a Structured Path to Master System Design Too? Donβt Miss This!