Sort Each Row of a NumPy Array Ascending Without Mutating the Input
Quick Overview
Sort the values in each row of a 2-D NumPy array in ascending order and return a new array without changing the input. It tests whether you choose the right axis and know which NumPy sort calls return a copy and which work in place.
Sort Each Row of a NumPy Array Ascending Without Mutating the Input
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 2-D numeric NumPy array, return a new array with each row's values sorted ascending along `axis=1`. Row count and order are preserved, and values never move between rows. Do not mutate the input.
Example:
```python
a = np.array([[3, 1, 2],
[9, 7, 8]])
# Output:
# [[1, 2, 3],
# [7, 8, 9]]
```
```hint Copy or in place
NumPy can sort through a method on the array or through a module-level function. Check which of the two returns a new array and which one changes the array it is called on.
```
### What a Strong Answer Covers
- Which axis to sort along so that every value stays inside its own row
- Returning a new array while leaving the input untouched
- Time and space cost for an m×n array
- Behavior on edge inputs such as `NaN` values or a 1-D array
### Follow-up Questions
- How would you sort each row in descending order, and where do `NaN` values end up?
- How would you reorder whole rows by the values in one column, keeping each row intact?
- Given a second array of the same shape, how would you rearrange it with the same per-row order used to sort `a`?
Overview: Sort the values in each row of a 2-D NumPy array in ascending order and return a new array without changing the input. It tests whether you choose the right axis and know which NumPy sort calls return a copy and which work in place.
Given a 2-D numeric NumPy array, return a new array with each row's values sorted ascending along axis=1. Row count and order are preserved, and values never move between rows. Do not mutate the input.