Find the index of the first NumPy array element above a threshold
Quick Overview
Write a vectorized NumPy function that returns the index of the first element strictly greater than a threshold, or -1 when nothing qualifies. It tests boolean masks, how argmax behaves on an all-False array, empty inputs and early exit on very large arrays.
Find the index of the first NumPy array element above a threshold
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Given a 1-D NumPy array `arr` and a scalar threshold `t`, return the 0-based index of the first element strictly greater than `t`, or `-1` if none exceeds it.
Requirements:
- Fully vectorized: no Python `for`/`while` loop over elements.
- Return a plain Python `int`.
- Return `-1` when no element satisfies `arr > t` or the array is empty.
Examples:
```python
arr = np.array([1, 3, 5, 2, 8])
t = 4
# Output: 2 (arr[2] == 5 is the first element > 4)
arr = np.array([1, 2, 3])
t = 10
# Output: -1 (nothing exceeds t)
```
```hint A reduction that reports a position
Some NumPy reductions return where a value occurs instead of the value itself. Think about what the largest value of a boolean array is and where such a reduction would point.
```
```hint Test the empty cases
Run your approach on a mask with no `True` values and on an empty array, and compare the result with a real match at index 0.
```
### What a Strong Answer Covers
- Finds the first match with vectorized operations only, with no loop over elements.
- Tells a real match at index 0 apart from the no-match case.
- Handles an empty array without raising an error.
- Returns a Python `int` and states the time and space cost.
### Follow-up Questions
- Why does `argmax` alone fail here, and how do you fix it?
- How would this scale on a huge array where the match is likely near the front?
- How would you return the first index above `t` for every row of a 2-D array, with `-1` for rows that have no match?
Overview: Write a vectorized NumPy function that returns the index of the first element strictly greater than a threshold, or -1 when nothing qualifies. It tests boolean masks, how argmax behaves on an all-False array, empty inputs and early exit on very large arrays.