Return the k largest values of a 1-D NumPy array in descending order, using np.argpartition to avoid a full sort. The question tests what argpartition guarantees about the kth position, the k = 0 and k = len(a) boundaries, and the time cost compared with sorting the whole array.
Given a 1-D array `a` and an integer `k`, return the `k` largest elements as a NumPy array in descending order. Use `np.argpartition` to select the top-k indices without fully sorting `a`, then sort only that slice.
For example:
```python
a = np.array([3, 1, 9, 7, 2, 8])
k = 3
# Output: array([9, 8, 7])
```
```hint What argpartition guarantees
Check what `np.argpartition` promises about the order on each side of the `kth` position, and which `kth` value puts the k largest at the end.
```
```hint Boundary values of k
Run your slice by hand with `k = 0` and with `k = len(a)` before calling it done.
```
### Constraints & Assumptions
- `0 <= k <= len(a)`
- `a` is 1-D and numeric.
- Ties may be returned in any relative order.
### What a Strong Answer Covers
- Which `kth` argument to pass to `np.argpartition`, and why the last `k` positions then hold the top-k indices.
- Why the selected block still needs sorting, and how to get descending order.
- The `k = 0` and `k = len(a)` boundaries.
- Time and space complexity compared with a full sort.
### Follow-up Questions
- Why is `argpartition` faster than a full `sort` here?
- How would you extend this to return the top-k along each row of a 2-D array?
- How do NaN values affect the result, and how would you exclude them?
Overview: Return the k largest values of a 1-D NumPy array in descending order, using np.argpartition to avoid a full sort. The question tests what argpartition guarantees about the kth position, the k = 0 and k = len(a) boundaries, and the time cost compared with sorting the whole array.
Given a 1-D array a and an integer k, return the k largest elements as a NumPy array in descending order. Use np.argpartition to select the top-k indices without fully sorting a, then sort only that slice.
For example:
a = np.array([3, 1, 9, 7, 2, 8])
k = 3
# Output: array([9, 8, 7])
Constraints & Assumptions
0 <= k <= len(a)
a
is 1-D and numeric.
Ties may be returned in any relative order.
What a Strong Answer Covers Guidance
Which
kth
argument to pass to
np.argpartition
, and why the last
k
positions then hold the top-k indices.
Why the selected block still needs sorting, and how to get descending order.
The
k = 0
and
k = len(a)
boundaries.
Time and space complexity compared with a full sort.
Follow-up Questions Guidance
Why is
argpartition
faster than a full
sort
here?
How would you extend this to return the top-k along each row of a 2-D array?
How do NaN values affect the result, and how would you exclude them?