#3843

First Element with Unique Frequency

Medium
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 two hash maps to count frequencies and track unique counts efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each number using a hash map.
  2. 2Step 2: Count how many numbers have each frequency using a second hash map.
  3. 3Step 3: Iterate through the original array to find the first number with a unique frequency.
solution.py8 lines
1def firstUnique(nums):
2    from collections import Counter
3    freq = Counter(nums)
4    freqCount = Counter(freq.values())
5    for num in nums:
6        if freqCount[freq[num]] == 1:
7            return num
8    return -1

Complexity note: Two passes through the array yield linear time complexity, with additional space for hash maps.

  • 1Unique frequency means no other number shares that count.
  • 2Order of appearance matters for the final output.

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