Min-Max Scaling (from Scratch)

MEDIUM

Implement a function that performs Min-Max scaling on a given 1D NumPy array. The function should transform the features to a range, typically [0, 1]. Do not use scikit-learn's MinMaxScaler.

The formula for Min-Max scaling is:

Xscaled = (X - Xmin) / (Xmax - Xmin)

Handle the edge case where X_max - X_min is zero (i.e., all elements in the array are the same). In this case, all scaled values should be 0 (or 0.5, or as specified).

Examples:

Example 1:

Input: arr = np.array([10, 20, 30, 40, 50])
Output: np.array([0.  , 0.25, 0.5 , 0.75, 1.  ])

Example 2:

Input: arr = np.array([15, 5, 20, 10])
Output: np.array([0.666..., 0.    , 1.    , 0.333...])

Example 3 (Edge Case):

Input: arr = np.array([7, 7, 7])
Output: np.array([0., 0., 0.])  (or [0.5, 0.5, 0.5] depending on convention for this case)

Constraints:

  • The input arr will be a 1D NumPy array of numbers.
  • The array can contain positive, negative, or zero values.
  • The array will not be empty.

Function Signature (Python):

import numpy as np

class Solution:
    def min_max_scale(self, arr: np.ndarray) -> np.ndarray:
        # Your code here
        pass

 

Nerchuko Academy · Free DS Interview Prep