Find minimum and most frequent number efficiently
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: Find minimum and most frequent number efficiently evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= nums.length <= 10^5 (an empty array returns (None, None))
- -10^9 <= nums[i] <= 10^9
- Values may be negative, zero, or duplicated.
- On a frequency tie, returning any one of the tied values is acceptable; the reference returns the first to reach the running max count.
Examples
Input: ([4, 1, 2, 2, 3, 1, 1],)
Expected Output: (1, 1)
Explanation: Minimum is 1. Frequencies: 1->3, 2->2, others 1. Most frequent is 1.
Input: ([5],)
Expected Output: (5, 5)
Explanation: Single element: it is both the minimum and the most frequent.
Input: ([],)
Expected Output: (None, None)
Explanation: Empty array returns (None, None).
Input: ([-3, -3, -1, 0, 7, 7, 7],)
Expected Output: (-3, 7)
Explanation: Minimum is -3 (negatives handled). 7 occurs 3 times, the most of any value.
Input: ([2, 2, 9, 9, 1],)
Expected Output: (1, 2)
Explanation: Minimum is 1. 2 and 9 both occur twice (a tie); 2 reaches count 2 first scanning left to right, so 2 is returned.
Input: ([10, 20, 30, 40],)
Expected Output: (10, 10)
Explanation: Minimum is 10. All values are distinct (frequency 1); the first element 10 is returned as most frequent.
Hints
- The O(n^2) baseline recounts the frequency of every element by scanning the array each time. Can you count all frequencies in one pass instead?
- A hash map from value to count gives O(1) amortized counting. Build it while you also track the running minimum so you only traverse the array once.
- Update the best (most frequent) candidate inline: whenever an element's new count strictly exceeds the current best count, make it the new best. This naturally yields the first value to reach each new maximum.
- Trade-off: you spend O(n) extra memory for the count map to bring time from O(n^2) down to O(n).