#3866

First Unique Even Element

Easy
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a hash map to count occurrences of each even number, then find the first unique even number in a single pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a hash map to count occurrences of each even number.
  2. 2Step 2: Iterate through the array again to find the first even number with a count of 1.
  3. 3Step 3: Return that number or -1 if none exists.
solution.py9 lines
1def first_unique_even(nums):
2    count = {}
3    for num in nums:
4        if num % 2 == 0:
5            count[num] = count.get(num, 0) + 1
6    for num in nums:
7        if num % 2 == 0 and count[num] == 1:
8            return num
9    return -1

Complexity note: We traverse the array twice, leading to linear time complexity, while using extra space for the hash map.

  • 1Even numbers are divisible by 2.
  • 2Counting occurrences helps identify uniqueness.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.