Talentd
FleetCode

3843. First Element with Unique Frequency

Medium69.9% acceptance

You are given an integer array nums.

Return an integer denoting the first element (scanning from left to right) in nums whose frequency is unique. That is, no other integer appears the same number of times in nums. If there is no such element, return -1.

Example 1:

Input: nums = [20,10,30,30]

Output: 30

Explanation:

  • 20 appears once.
  • 10 appears once.
  • 30 appears twice.
  • The frequency of 30 is unique because no other integer appears exactly twice.

Example 2:

Input: nums = [20,20,10,30,30,30]

Output: 20

Explanation:

  • 20 appears twice.
  • 10 appears once.
  • 30 appears 3 times.
  • The frequency of 20, 10, and 30 are unique. The first element that has unique frequency is 20.

Example 3:

Input: nums = [10,10,20,20]

Output: -1

Explanation:

  • 10 appears twice.
  • 20 appears twice.
  • No element has a unique frequency.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105

Hints open one at a time

Hint 1
Use two hash maps: one freq and one freqCount
Hint 2
First pass: for each x in nums do freq[x] += 1
Hint 3
Build counts of frequencies: for each f in values of freq do freqCount[f] += 1
Hint 4
Scan nums from left to right and return the first x with freqCount[freq[x]] == 1; return -1 if none
8:28
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def firstUniqueFreq(self, nums: List[int]) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[20,10,30,30]
Input
[20,20,10,30,30,30]
Input
[10,10,20,20]
Your code is saved on this device.Solution