Deduplicate a NumPy array and return its distinct values in ascending order
Quick Overview
Write a NumPy function that removes duplicates from a 1-D array and returns each distinct value once in ascending order. It tests NumPy set routines, sort-based deduplication, the cost of sorting and edge cases such as empty arrays and NaN values.
Deduplicate a NumPy array and return its distinct values in ascending order
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D NumPy array `arr` that may contain duplicates, return a new 1-D array containing each distinct value exactly once, sorted in ascending order.
For example:
```python
arr = np.array([3, 1, 2, 3, 1, 5])
# Output: array([1, 2, 3, 5])
```
```hint Sort first
After a sort, duplicate values sit next to each other. NumPy also has a set routine that does the sorting for you.
```
### What a Strong Answer Covers
- A function that returns a new 1-D NumPy array with each value once, in ascending order, without modifying the input.
- Why the result comes out sorted without a separate sort call, and what that costs in time.
- How the function behaves on an empty array, NaN values and an input that is not 1-D.
- A version that does not depend on the one-call shortcut.
### Follow-up Questions
- How would you also return the count of each distinct value?
- How would you implement this with only a sort and an element-wise comparison?
- How would you keep the distinct values in order of first appearance instead of sorted order?
- Why is converting to a Python `set` and back a weaker answer?
Overview: Write a NumPy function that removes duplicates from a 1-D array and returns each distinct value once in ascending order. It tests NumPy set routines, sort-based deduplication, the cost of sorting and edge cases such as empty arrays and NaN values.
Given a 1-D NumPy array arr that may contain duplicates, return a new 1-D array containing each distinct value exactly once, sorted in ascending order.