Facebook Pixel

3866. First Unique Even Element

EasyArrayHash TableCounting
LeetCode β†—

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:

  1. It is an even number (i.e., x % 2 == 0).
  2. 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.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

How We Pick the Algorithm

Why Hash Table / Counting?

This problem maps to Hash Table / Counting through a short path in the full flowchart.

Fastlookup orcounting/grouping?yesLinkedlist?noHash Table /Counting

Two-pass counting: build frequency map, then scan for the first even element with count exactly 1.

Open in Flowchart

Intuition

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:

  1. Build a counter cnt using Counter(nums). After this step, cnt[x] tells us exactly how many times the value x appears in nums. This takes a single pass over the array.

  2. Traverse nums again from left to right. For each element x, we check two conditions together:

    • x % 2 == 0, meaning x is even.
    • cnt[x] == 1, meaning x appears exactly once in the whole array.
  3. The moment both conditions hold, we have found the earliest qualifying number by index, so we return x right away.

  4. 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:

ValueCount
42
22
61
31

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):

IndexxEven? (x % 2 == 0)Unique? (cnt[x] == 1)Action
04βœ… Yes❌ No (count is 2)Skip
12βœ… Yes❌ No (count is 2)Skip
24βœ… Yes❌ No (count is 2)Skip
36βœ… 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
18
1class 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}
28
1class 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};
23
1/**
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}
32

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the array nums. Building the Counter requires a single pass over all n elements, taking O(n) time. The subsequent for loop also iterates over the array at most once, performing constant-time operations (the parity check x % 2 == 0 and the dictionary lookup cnt[x]) for each element, contributing another O(n). The total time is therefore O(n).

  • Space Complexity: O(M), where M is the range of distinct integer values in the array (100 in this problem). The Counter object stores one entry per unique value in nums, so the extra space scales with the number of distinct integers, which is bounded by M. No other auxiliary data structures grow with the input, hence the space complexity is O(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 == 0 works correctly, so the standard check num % 2 == 0 is safe. However, in languages like C++ or Java, % can return a negative remainder (-3 % 2 == -1), so a check like num % 2 == 1 to detect odd numbers would fail for negatives. Always test num % 2 == 0 for evenness, never num % 2 == 1 for 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 Roadmap
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Get a Personalized Study Roadmap:

How many ways can you arrange the three letters A, B and C?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More