Detect Outliers
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
Problem
Given a list of numbers and multiplier k, compute the mean. Return the sorted list of indices where the value exceeds k * mean.
Most values are normal. Some are suspicious.
Example 1
Input:
values = [10,12,11,50,9,13,45], k = 2
Output:
[3,6]
Example 2
Input:
values = [1,1,1,1], k = 2
Output:
[]
Worked solution and explanation
Why this problem exists in real interviews
Flagging values that deviate from the mean by a threshold factor is a basic statistical filtering operation used in monitoring pipelines. It tests two-pass processing: compute the mean first, then filter.
Break down the requirements
Step 1: Compute the mean of the list
Sum all values and divide by the count. This requires a first pass through the data.
Step 2: Find indices where the value exceeds k times the mean
In a second pass, compare each value against k * mean and collect indices that exceed it.
The solution
def detect_outliers(values, k):
total = 0
for v in values:
total += v
mean = total / len(values)
threshold = k * mean
result = []
for i in range(len(values)):
if values[i] > threshold:
result.append(i)
return resultCommon follow-up questions
- What if you needed outliers based on standard deviation instead of mean? (Tests computing both mean and standard deviation in a two-pass approach.)
- How would you handle streaming data where the mean evolves? (Tests online algorithms like Welford's method for running mean and variance.)
- What if the list contains negative values? (Tests whether the threshold logic still holds when the mean itself could be negative.)