First Unique Even Element Problem
#3866
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3866.
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
Solution
Approach: Counting
Count how many times every value occurs (values are at most 100, so an array works). Then walk through nums again and return the first even value whose count is exactly 1, or -1 if there is none.
Complexity: O(n) time and O(M) space, where M = 100 is the value range.
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