Smallest Pair With Different Frequencies Problem
#3852
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 3852.
You are given an integer array nums.
Consider all pairs of distinct values x and y from nums such that:
x < yxandyhave different frequencies innums.
Among all such pairs:
- Choose the pair with the smallest possible value of
x. - If multiple pairs have the same
x, choose the one with the smallest possible value ofy.
Return an integer array [x, y]. If no valid pair exists, return [-1, -1].
Example 1:
Input: nums = [1,1,2,2,3,4]
Output: [1,3]
Explanation:
The smallest value is 1 with a frequency of 2, and the smallest value greater than 1 that has a different frequency from 1 is 3 with a frequency of 1. Thus, the answer is [1, 3].
Example 2:
Input: nums = [1,5]
Output: [-1,-1]
Explanation:
Both values have the same frequency, so no valid pair exists. Return [-1, -1].
Example 3:
Input: nums = [7]
Output: [-1,-1]
Explanation:
There is only one value in the array, so no valid pair exists. Return [-1, -1].
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Hash Table
Count how often each value occurs. The pair [x, y] needs x < y and different counts, and we want the smallest x, then the smallest y. So take x as the smallest value in the array and look for the smallest value y whose count differs from the count of x. If there is none, return [-1, -1].
Complexity: O(n) time and O(n) space.
from collections import Counter
from math import inf
class Solution:
def minDistinctFreqPair(self, nums: List[int]) -> List[int]:
cnt = Counter(nums)
x = min(cnt.keys())
min_y = inf
for y in cnt.keys():
if y < min_y and cnt[x] != cnt[y]:
min_y = y
return [-1, -1] if min_y == inf else [x, min_y]