Build a vectorized NumPy boolean mask of outliers using the 1.5 IQR rule
Quick Overview
Write a vectorized NumPy function that returns a boolean mask flagging outliers under the 1.5 times IQR rule, with exclusive fences. It tests percentile computation, broadcasting and boundary handling, and asks how to extend the rule to 2-D arrays and inputs with NaN values.
Build a vectorized NumPy boolean mask of outliers using the 1.5 IQR rule
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Write `iqr_outliers(a: np.ndarray) -> np.ndarray` returning a boolean mask (same shape as `a`) marking outliers under the 1.5*IQR rule. Compute quartiles with `np.percentile(a, [25, 75])`, let `IQR = Q3 - Q1`, and flag values below `Q1 - 1.5*IQR` or above `Q3 + 1.5*IQR`.
Requirements:
- Bounds are exclusive: values exactly on a fence are not outliers.
- Vectorized NumPy only, no Python loops.
```python
a = np.array([10, 12, 11, 13, 12, 100])
iqr_outliers(a)
# array([False, False, False, False, False, True])
```
```hint Mind the fences
Compute the two fences as scalars first and let broadcasting compare them against the whole array. Then check which comparison operators keep a value sitting exactly on a fence out of the mask.
```
### Constraints & Assumptions
- `a` is a 1-D numeric array with no NaNs.
### What a Strong Answer Covers
- Getting both quartiles from one `np.percentile` call and deriving the IQR and the two fences
- A vectorized mask with the same shape as `a` that respects the exclusive bounds
- Time and space complexity
- Edge cases such as an IQR of 0, very small arrays, and NaN or empty input
### Follow-up Questions
- How would you extend this to work column-wise on a 2-D array?
- How would you handle NaNs in the input?
- What happens when more than half of the values are identical, and is the result still useful?
Overview: Write a vectorized NumPy function that returns a boolean mask flagging outliers under the 1.5 times IQR rule, with exclusive fences. It tests percentile computation, broadcasting and boundary handling, and asks how to extend the rule to 2-D arrays and inputs with NaN values.
Write iqr_outliers(a: np.ndarray) -> np.ndarray returning a boolean mask (same shape as a) marking outliers under the 1.5*IQR rule. Compute quartiles with np.percentile(a, [25, 75]), let IQR = Q3 - Q1, and flag values below Q1 - 1.5*IQR or above Q3 + 1.5*IQR.
Requirements:
Bounds are exclusive: values exactly on a fence are not outliers.