easyFeature engineering
Min-Max Feature Scaling
Rescale a numeric feature to the range 0 to 1 with min-max scaling, and handle the constant-feature case that breaks the naive formula.
JavaScript or Python
Many models, such as k-nearest neighbours and anything trained with gradient descent, work better when features share a similar range. Min-max scaling maps each value v to (v - min) / (max - min), so the smallest value becomes 0 and the largest becomes 1.
Given a non-empty list of numbers, return the scaled list in the same order. If every value is the same, return a list of zeros instead of dividing by zero. Results are checked to six significant digits.
Examples
Example 1
Input: values = [10, 20, 30] Output: [0, 0.5, 1] Why: min 10, max 30, range 20
Example 2
Input: values = [5, 5, 5] Output: [0, 0, 0] Why: A constant feature has no range
Constraints
1 <= values.length <= 10^5-10^9 <= values[i] <= 10^9
Hints
Hint 1
Find the minimum and maximum first.
Hint 2
If max equals min, every scaled value is 0.
Solution
Show the solution (try it yourself first)
Find the minimum and maximum, then map each value with (v - lo) / (hi - lo). The only trap is a constant feature, where the range is zero: return zeros (a constant feature carries no information, and many pipelines drop it).
def min_max_scale(values):
lo, hi = min(values), max(values)
if hi == lo:
return [0.0 for _ in values]
return [(v - lo) / (hi - lo) for v in values]Complexity
Time O(n), space O(n). In a real project you compute lo and hi on the training split only and reuse them for validation, test and production data; computing them on all the data is a form of leakage. Min-max scaling is sensitive to outliers, so standardisation (z-scores) or robust scaling is often preferred, a common follow-up question.
Found a mistake in this problem, its tests or the solution?