#3852

Smallest Pair With Different Frequencies

Easy
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(n)

Use a frequency map to count occurrences and then find the smallest pair with different frequencies efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count frequencies of each number using a hash map.
  2. 2Step 2: Sort the unique numbers based on their values.
  3. 3Step 3: Iterate through sorted unique numbers to find the first pair with different frequencies.
solution.py8 lines
1def smallest_pair(nums):
2    from collections import Counter
3    freq = Counter(nums)
4    unique = sorted(freq.keys())
5    for i in range(len(unique) - 1):
6        if freq[unique[i]] != freq[unique[i + 1]]:
7            return [unique[i], unique[i + 1]]
8    return [-1, -1]

Complexity note: The complexity is linearithmic due to sorting the unique elements.

  • 1Use frequency counting to simplify comparisons.
  • 2Sorting helps in efficiently finding pairs.

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