Taro Logo

Smallest Pair With Different Frequencies

#2 Most AskedEasy
0 views
Topics:
Arrays

You are given an integer array nums.

Consider all pairs of distinct values x and y from nums such that:

  • x < y
  • x and y have different frequencies in nums.

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 of y.

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 <= 100
  • 1 <= nums[i] <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if no such pair of distinct numbers with different frequencies exists in the array?
  2. By "distinct numbers", do you mean we need to pick two numbers that have different numerical values, or does it refer to two distinct elements by index?
  3. How should the resulting pair be ordered when returned (e.g., sorted in ascending order, or in the order they first appear in the array)?
  4. If there are multiple valid pairs that have different frequencies, which one should be prioritized to satisfy the "lexicographically smallest possible values" criteria?
  5. Can the input array contain negative numbers, zeros, or be empty/have fewer than two elements?

Brute Force Solution

Approach

The goal is to find a pair of distinct numbers with different occurrences such that the first number is as small as possible, followed by the smallest possible second number. We first count the frequencies of all numbers in the input array. Then, iterating through sorted unique elements allows us to greedily find the valid pair that satisfies the minimality conditions.

Here's how the algorithm would work step-by-step:

  1. Count the frequency of each number using a hash map.
  2. Extract the unique numbers and sort them in ascending order.
  3. Iterate through each unique element as a candidate for the first element of the pair.
  4. For each first element, check subsequent sorted elements to find the first one with a different frequency.
  5. Immediately return the first valid pair found since elements are inspected in lexicographical order.
  6. Return [-1, -1] if no valid pair exists after checking all combinations.

Code Implementation

from collections import Counter

def smallest_pair_with_different_frequencies(nums):
    # Count the frequency of each unique number in the array.
    frequency_map = Counter(nums)
    # Get all unique values in sorted ascending order.
    sorted_unique_values = sorted(frequency_map.keys())
    # Search for the first pair with different frequencies.
    for first_index in range(len(sorted_unique_values)):
        first_value = sorted_unique_values[first_index]
        for second_index in range(first_index + 1, len(sorted_unique_values)):
            second_value = sorted_unique_values[second_index]
            if frequency_map[first_value] != frequency_map[second_value]:
                return [first_value, second_value]
    # Return default pair if no such combination exists.
    return [-1, -1]

Big(O) Analysis

Time Complexity
O(N + U log U + U^2) – Counting occurrences takes O(N) time, where N is the length of nums. Sorting the U unique values takes O(U log U) time. The nested search takes at most O(U^2) iterations, where U is at most 100, making the execution extremely fast.
Space Complexity
O(U) – The frequency map and the sorted list of unique numbers store at most U distinct elements, which requires O(U) auxiliary space.

Optimal Solution

Approach

This solution finds the lexicographically smallest pair of distinct numbers with different frequencies in an array. It counts the frequencies of each unique element and sorts the distinct elements in ascending order. By iterating through all pairs in lexicographical order, the first valid pair encountered is guaranteed to be optimal.

Here's how the algorithm would work step-by-step:

  1. Compute the frequency of each unique number using a hash map.
  2. Extract the unique numbers and sort them in ascending order.
  3. Iterate over each unique number as the candidate for the smaller element.
  4. For the current candidate, scan through all strictly greater sorted elements.
  5. Check if the greater element has a frequency different from the current candidate.
  6. Return the pair immediately upon finding the first match.
  7. If no such pair is found after checking all combinations, return [-1, -1].

Code Implementation

from collections import Counter

def smallest_pair_with_different_frequencies(nums):
    # Count the frequency of each distinct number in nums
    frequencies = Counter(nums)
    # Get all distinct numbers sorted in ascending order
    sorted_values = sorted(frequencies.keys())
    
    # Iterate through each candidate for the first element
    for outer_index in range(len(sorted_values)):
        first_value = sorted_values[outer_index]
        first_count = frequencies[first_value]
        # Find the smallest greater element with a different frequency
        for inner_index in range(outer_index + 1, len(sorted_values)):
            second_value = sorted_values[inner_index]
            if frequencies[second_value] != first_count:
                return [first_value, second_value]
                
    return [-1, -1]

Big(O) Analysis

Time Complexity
O(U log U + U^2) – Here U is the number of unique elements, which is bounded by both N (array length) and 100. Counting frequencies takes O(N) time, sorting unique elements takes O(U log U) time, and scanning pairs takes at most O(U^2) time, which is well within limits for N <= 100.
Space Complexity
O(U) – The hash map and the list of sorted unique values require memory proportional to the number of unique elements in the input, which is at most min(N, 100).

Edge Cases

Empty or single-element array
How to Handle:
Return a default indicator or empty result immediately since a pair requires at least two numbers.
Array where all elements have the exact same frequency
How to Handle:
Return an empty result or handle according to problem constraints since no pair with different frequencies exists.
Input contains negative numbers and zeros
How to Handle:
Use a hash map instead of a direct-access array for frequencies to safely handle negative keys and zero.
Array with only two distinct elements having the same frequency
How to Handle:
Detect that all available distinct elements share a frequency and return that no valid pair can be formed.
Extremely large input size with millions of elements
How to Handle:
Ensure linear time complexity by building frequency maps in one pass and sorting only the small set of distinct values.
Multiple valid pairs satisfying the different frequency condition
How to Handle:
Sort the distinct elements or candidate pairs to deterministically select the lexicographically smallest pair.
Values exceeding standard 32-bit integer limits
How to Handle:
Use 64-bit integers or native language types that safely handle extreme boundary values without overflow.
All elements are identical
How to Handle:
Recognize that there is only one distinct number, making it impossible to form a pair of distinct numbers.
0/8 completed