Find the most frequent value in a NumPy array, returning the smallest value on ties
Quick Overview
Return the most frequent value of a 1-D NumPy array that can hold negatives and repeats, picking the smallest value when counts tie. It tests vectorized counting, how sort order and argmax decide ties, dtype limits of counting functions, and complexity.
Find the most frequent value in a NumPy array, returning the smallest value on ties
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D NumPy array `arr` that may contain negative numbers and repeated values, return its most frequent value. When several values tie for the highest frequency, return the smallest of them.
```python
arr = np.array([3, -1, 3, -1, 2])
most_frequent(arr) # -> -1
```
Both 3 and -1 occur twice, and -1 is the smaller of the two.
```hint Counts and order
Look for a NumPy function that returns the distinct values together with how often each occurs, and check the order in which it returns them.
```
### What a Strong Answer Covers
- Counting occurrences of each distinct value without a Python loop over elements.
- A tie rule that returns the smallest tied value, with the reason it holds.
- Behavior on negative values and non-integer dtypes.
- Time and space complexity of the chosen approach.
- Edge cases such as an empty array.
### Follow-up Questions
- What breaks if you use `np.bincount` instead, and when is it the better tool?
- How would you return every value tied for the highest count?
- Why does `collections.Counter(arr).most_common(1)` not meet the tie rule?
- How should the function treat NaN in a float array?
Overview: Return the most frequent value of a 1-D NumPy array that can hold negatives and repeats, picking the smallest value when counts tie. It tests vectorized counting, how sort order and argmax decide ties, dtype limits of counting functions, and complexity.
Given a 1-D NumPy array arr that may contain negative numbers and repeated values, return its most frequent value. When several values tie for the highest frequency, return the smallest of them.