Skip to content
UniCircle
MediumCodingData preprocessing

Fill missing values with the median, then min-max scale

Question DS-PRE-104

A column of sensor readings has gaps, written as NA. Clean it in two steps:

  1. Impute: replace every NA with the median of the values that are present.
  2. Min-max scale the completed column to [0, 1]: x′ = (x − min) / (max − min). If max = min, every scaled value is 0.

Print the scaled values with 4 decimals, in the original order.

Constraints

  • 1 ≤ n ≤ 3000
  • −10^6 ≤ each value ≤ 10^6

Input and output

Input
First line: n. Second line: n tokens, each an integer or `NA` (at least one integer).
Output
One line: n numbers with 4 decimals, separated by spaces.

Examples

Input 1

6
10 NA 30 20 NA 50

Output

0.0000 0.3750 0.5000 0.2500 0.3750 1.0000

The present values 10 20 30 50 have median 25. The completed column is 10 25 30 20 25 50, min 10, max 50.

Input 2

3
7 NA 7

Output

0.0000 0.0000 0.0000

After filling in 7, the column is constant, so every value scales to 0.

Show hints
  • Compute the median only from the values that are present.
  • After imputation, min and max are taken over the completed column. The median always lies between them, so they are the same as for the present values.
Show the explanation
Python
present = sorted(int(t) for t in toks if t != "NA")
m = len(present)
med = present[m // 2] if m % 2 else (present[m // 2 - 1] + present[m // 2]) / 2
col = [med if t == "NA" else int(t) for t in toks]
lo, hi = min(col), max(col)
scaled = [0.0 if hi == lo else (v - lo) / (hi - lo) for v in col]

Why the median? It is robust: one huge faulty reading moves the mean a lot but barely moves the median. Mean imputation suits roughly symmetric data. For categories, use the mode. More advanced options: KNN imputation, model-based imputation, or adding an "was missing" indicator column so the model can learn whether missingness itself carries information.

Data leakage. In a real ML pipeline, compute the median, min and max on the training split only, then apply those same numbers to the validation and test data. scikit-learn's SimpleImputer and MinMaxScaler inside a Pipeline do this: fit on train, transform on everything. Computing them on the full data set leaks information about the test set into training.

Min-max scaling vs standardisation

  • Min-max maps values to [0, 1]. It is sensitive to outliers, because one extreme value squashes everything else together.
  • Standardisation (z = (x − μ)/σ) centres the data at 0 with unit variance. It is preferred for many linear models, SVMs and PCA.
  • Tree-based models (decision trees, random forests, gradient boosting) generally do not need either.

Guard the constant column: dividing by max − min = 0 would crash.

Original UniCircle question. Last reviewed 22 Oct 2026.