← back

Shift and Scale Array to Target Range

#141 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Scale and shift an array of values so that they map to a specified target range [new_min, new_max]. This is Min-Max normalization to an arbitrary range.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np

def shift_and_scale(arr: np.ndarray, new_min: float, new_max: float) -> np.ndarray:
    old_min = np.min(arr)
    old_max = np.max(arr)

    if old_max == old_min:
        return np.full_like(arr, (new_min + new_max) / 2.0, dtype=float)

    # Normalize to [0, 1] then scale to [new_min, new_max]
    normalized = (arr - old_min) / (old_max - old_min)
    return normalized * (new_max - new_min) + new_min

Explanation

  1. Find the minimum and maximum of the input array.
  2. Normalize each element to [0, 1] by subtracting the min and dividing by the range.
  3. Scale to the target range by multiplying by (new_max - new_min) and adding new_min.
  4. Handle the edge case where all values are equal by returning the midpoint of the target range.

Complexity

  • Time: O(n) where n is the number of elements
  • Space: O(n) for the output array