Greedy Collinearity Feature Filter and Atomic CSV Cleaner

Easy · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

Before fitting a linear forecasting model, data engineering workflows typically perform two steps: safe out-of-place CSV scrubbing and greedy screening of collinear predictors. Build both helpers in Python:

def select_uncorrelated_features(
    rows: List[Dict[str, float]],
    target_col: str,
    collinearity_threshold: float = 0.85,
) -> List[str]:

def sanitize_dataset(
    src_path: str,
    dst_path: str,
    required_columns: list[str],
) -> int:

1. Greedy Predictor Screening (select_uncorrelated_features — Automated Judge Entry Point)

rows represents a numeric table as a list of row dictionaries sharing identical keys (str -> float). Screen every predictor column (all keys other than target_col) as follows:

  • Ignore any predictor column whose entries are all identical (zero variance makes Pearson correlation undefined). Return [] immediately if rows is empty, if target_col itself is constant, or if no non-constant predictor exists.
  • Measure each remaining predictor's linear strength against target_col using the absolute Pearson correlation coefficient |r|.
  • Order predictors from highest to lowest |r| against target_col. Resolve exact ties (up to standard floating-point precision) in ascending alphabetical (ASCII) order of column name.
  • Traverse the sorted predictors in order. Accept a predictor if and only if its absolute Pearson correlation |r| with each predictor accepted so far satisfies |r| < collinearity_threshold (predictors rejected earlier never block subsequent ones).
  • Return the accepted column names in acceptance order.

2. Crash-Safe CSV Scrubbing (sanitize_dataset)

  • Read CSV lines from src_path without ever altering src_path (raise ValueError if src_path and dst_path resolve to the same file, if no header line exists, or if any column in required_columns is missing from the header).
  • Keep the header row plus every data row whose column count matches the header and whose cells in required_columns all parse as finite floating-point numbers (rejecting blanks, text, NaN, and inf).
  • Stage the scrubbed CSV into a sibling temporary file inside dst_path's directory, flush buffers to storage, and swap it onto dst_path in one atomic rename (os.replace). Delete any temporary file if an error or interrupt occurs mid-flight so dst_path is never left half-written. Return how many data rows survived.

Examples

Example 1

Input:
  rows = [
      {"price": 10, "sqft": 1, "rooms": 2, "age": 8},
      {"price": 20, "sqft": 2, "rooms": 4, "age": 2},
      {"price": 30, "sqft": 3, "rooms": 5, "age": 6},
      {"price": 40, "sqft": 4, "rooms": 9, "age": 0},
  ]
  target_col = "price"
  collinearity_threshold = 0.85

Output: ["sqft", "age"]

Walk-through: Against "price", absolute correlations are |r(price, sqft)| = 1.0, |r(price, rooms)| ≈ 0.9648, and |r(price, age)| ≈ 0.7071 (r ≈ -0.7071). "sqft" is chosen first. "rooms" is dropped because |r(rooms, sqft)| ≈ 0.9648 >= 0.85. "age" is then compared against "sqft" (0.7071 < 0.85) and kept.

Example 2

Input:
  rows = [
      {"load": 4, "wind": -3, "solar": 3, "hydro": 2},
      {"load": 2, "wind": -1, "solar": 1, "hydro": -1},
      {"load": 0, "wind": 1, "solar": -1, "hydro": 1},
      {"load": -2, "wind": 3, "solar": -3, "hydro": -2},
  ]
  target_col = "load"
  collinearity_threshold = 0.75

Output: ["solar", "hydro"]

Walk-through: Both "solar" (r = +1.0) and "wind" (r = -1.0) achieve |r| = 1.0 with "load", while "hydro" has |r| ≈ 0.7071. Alphabetical tie-breaking puts "solar" ahead of "wind". "solar" is kept first, "wind" is rejected (|r(wind, solar)| = 1.0 >= 0.75), and "hydro" is kept (|r(hydro, solar)| ≈ 0.7071 < 0.75).

Constraints

  • 0 <= len(rows) <= 10^5 (correlations require at least 2 non-constant observations; smaller or constant inputs return []).
  • 1 <= len(rows[0]) <= 500 when rows is non-empty, and target_col is present in every row dictionary.
  • 0.0 <= collinearity_threshold <= 1.0.
  • All values in rows are finite int or float numbers.

Step-by-step walkthrough

  1. Restate the two utilities and interface details

    Data preparation before fitting a linear model needs two building blocks:

    1. sanitize_dataset(src_path, dst_path, required_columns): stream CSV records from src_path, skip malformed lines or rows lacking finite floats in required_columns, and publish the scrubbed CSV to dst_path atomically (another reader sees either the previous dst_path or the finished replacement, never a truncated file, while src_path stays untouched). Return how many data rows survived.
    2. select_uncorrelated_features(rows, target_col, collinearity_threshold=0.85): order predictor columns from strongest to weakest |r| (absolute Pearson correlation) against target_col with alphabetical tie-breaking, then accept a predictor only if its |r| against every predictor accepted so far satisfies |r| < collinearity_threshold.

    In starter.py, the automated judge tests select_uncorrelated_features on rows: List[Dict[str, float]] (a list of row dictionaries), and we include sanitize_dataset alongside it as a complete solution.

    Three clean rules keep every boundary case deterministic:

    • Constant columns have zero standard deviation (leaving r = 0 / 0 undefined); constant predictors are ignored, and a constant target returns [].
    • Rounding |r| to 12 decimal places prevents 10^-16 floating-point drift from disturbing exact ties or slipping past collinearity_threshold.
    • In sanitize_dataset, every cell listed in required_columns must parse as a finite float (rejecting "", "abc", "NaN", and "inf"), while non-required columns pass through unchanged.
  2. Understand Pearson correlation and why we precompute one matrix

    Pearson correlation (r) measures how closely two numeric columns x and y follow a straight line:

    mean_x = sum(x) / N,   mean_y = sum(y) / N
    
    r(x, y) = sum((x_i - mean_x) * (y_i - mean_y))
              -----------------------------------------------------------
              sqrt( sum((x_i - mean_x)^2) * sum((y_i - mean_y)^2) )
    

    r always lies between -1 and +1. A correlation of -0.95 means y moves in the exact opposite direction of x — which carries the same redundant linear information as +0.95! That is why we take the absolute value |r| both when ranking against the target and when screening pairs of predictors.

    Rather than recomputing O(N) dot products inside nested loops, we stack the target and all K valid candidate features into a (K + 1) x N array and call np.corrcoef once:

    all_series index:    0 (price)     1 (sqft)      2 (rooms)     3 (age)
                       +------------+-------------+-------------+-------------+
    0 (price)          |    1.00    | |r(p, sqft)|| |r(p, rooms)|| |r(p, age)| | <-- row 0 ranks features!
    1 (sqft)           | |r(sqft,p)||    1.00     | |r(s, rooms)|| |r(s, age)| |
    2 (rooms)          ||r(rooms,p)|| |r(rooms,s)||    1.00     | |r(r, age)| | <-- pairwise lookups!
    3 (age)            | |r(age, p)|| |r(age, s)| | |r(age, r)| |    1.00     |
                       +------------+-------------+-------------+-------------+
    

    After this single matrix computation, every correlation check in our greedy filter is an O(1) array lookup!

  3. Handle constant columns and floating-point tie noise

    Two numerical traps trip up many implementations:

    1. Constant columns (min(values) == max(values)): When all entries in a column are equal, its denominator in r(x, y) is 0, producing NaN. Because NaN >= threshold and NaN < threshold both evaluate to False, leaving NaN in the matrix silently corrupts sorting and filtering. Note that min(values) == max(values) is exact, whereas np.std([0.1, 0.1, 0.1]) == 0 is False (~1.4e-17) due to binary float rounding! We also return [] early if candidate_names is empty so np.corrcoef always receives at least 2 rows and always returns a 2-D matrix.
    2. Tiny float noise on ties and thresholds: A column a and its scaled copy 3 * a + 5 have mathematical correlation 1.0, yet float division can yield 0.9999999999999999. Without rounding, 0.9999999999999999 < 1.0 would wrongly keep an exact duplicate at threshold = 1.0, and tiny 1e-16 differences would break ties arbitrarily instead of alphabetically. Rounding |r| to 12 decimal places (np.round(..., 12)) eliminates 1e-16 noise cleanly.
    def column_values(rows: List[Dict[str, float]], col_name: str) -> List[float]:
        """Extract one named column from row dictionaries as a list of floats."""
        values = []
        for row in rows:
            values.append(float(row[col_name]))
        return values
    
    
    def is_constant(values: List[float]) -> bool:
        """Exact zero-variance check without floating-point mean rounding errors."""
        return min(values) == max(values)
    
  4. Rank candidates and run the greedy collinearity filter

    Python compares tuples from left to right. If we represent each candidate as (-target_corr, col_name, matrix_idx), calling .sort() puts the largest target_corr first (since -1.0 < -0.9648) and automatically breaks equal -target_corr ties in ascending alphabetical order of col_name ("solar" < "wind").

    Next, we walk through ranked_candidates in sorted order:

    • The very first candidate is always selected because selected_indices is initially empty.
    • Each later candidate is compared only against selected_indices (predictors we actually kept — a dropped predictor never blocks future candidates!).
    • Because the requirement is strictly less than (|r| < collinearity_threshold), any pair with abs_corr_matrix[candidate_idx, selected_idx] >= collinearity_threshold marks the candidate redundant.
    def greedy_filter(
        candidate_names: List[str],
        abs_corr_matrix: np.ndarray,
        collinearity_threshold: float,
    ) -> List[str]:
        ranked_candidates = []
        for idx, col_name in enumerate(candidate_names):
            matrix_idx = idx + 1
            target_corr = float(abs_corr_matrix[0, matrix_idx])
            ranked_candidates.append((-target_corr, col_name, matrix_idx))
        ranked_candidates.sort()
    
        selected_names = []
        selected_indices = []
        for _, col_name, candidate_idx in ranked_candidates:
            is_redundant = False
            for selected_idx in selected_indices:
                if abs_corr_matrix[candidate_idx, selected_idx] >= collinearity_threshold:
                    is_redundant = True
                    break
            if not is_redundant:
                selected_names.append(col_name)
                selected_indices.append(candidate_idx)
    
        return selected_names
    
  5. Walk through Example 1 step by step

    In Example 1, price = [10, 20, 30, 40], sqft = [1, 2, 3, 4], rooms = [2, 4, 5, 9], age = [8, 2, 6, 0], and collinearity_threshold = 0.85:

    Pairwise |r| values:
      |r(price, sqft)| = 1.0,  |r(price, rooms)| = 0.9648,  |r(price, age)| = 0.7071
      |r(sqft, rooms)| = 0.9648
      |r(sqft, age)|   = 0.7071
    
    Sorted candidates:
      1. (-1.0,    'sqft',  1) -> selected is [], keep 'sqft'             -> selected = ['sqft']
      2. (-0.9648, 'rooms', 2) -> |r(rooms, sqft)| = 0.9648 >= 0.85 -> DROP
      3. (-0.7071, 'age',   3) -> |r(age, sqft)|   = 0.7071 <  0.85 -> KEEP -> selected = ['sqft', 'age']
    

    Notice age is never compared against rooms because rooms was dropped. Output: ['sqft', 'age'].

  6. Build the atomic CSV cleaner: temp file + fsync + os.replace

    Why is open(dst_path, "w") dangerous in a data pipeline? Because "w" immediately wipes dst_path to 0 bytes, and if the process crashes or runs out of disk halfway through row 500,000, downstream readers see a truncated, corrupted CSV!

    The standard POSIX pattern for an atomic file update stages everything into a hidden sibling file first, then swaps directory pointers in one instant:

    src_path (opened read-only, streamed 1 row at a time)
       |
       v  validate header + finite floats in required_columns
    dst_dir/.tmp-8f3k2.csv   <-- 1. chmod 0644, write rows, flush() + os.fsync()
       |
       |  2. os.replace(tmp, dst_path)  [atomic on same filesystem!]
       v
    dst_path                 (if step 1 fails, remove .tmp file; old dst_path is untouched)
    

    Every line in that recipe solves a real production failure mode:

    • Same directory (dir=dst_dir): os.replace can only atomically rename within the same filesystem; /tmp is often a separate mount where os.replace raises OSError.
    • delete=False + try / except BaseException: keeps the temp file alive after closing so os.replace can rename it, while guaranteeing .tmp-* is deleted on any error (even KeyboardInterrupt).
    • os.chmod(..., 0o644) + os.fsync: NamedTemporaryFile defaults to 0600 (owner-only), which would lock out group readers after rename, and fsync forces data out of OS RAM buffers onto physical storage before replacing dst_path.
  7. Code sanitize_dataset

    def is_finite_float(text: str) -> bool:
        """Return True if text parses as a finite float (rejecting '', 'NaN', 'inf', 'abc')."""
        try:
            value = float(text)
        except ValueError:
            return False
        return math.isfinite(value)
    
    
    def row_is_valid(row: List[str], expected_width: int, required_positions: List[int]) -> bool:
        """Keep a row only if its column count matches the header and required cells are finite floats."""
        if len(row) != expected_width:
            return False
        for pos in required_positions:
            if not is_finite_float(row[pos]):
                return False
        return True
    
    
    def sanitize_dataset(src_path: str, dst_path: str, required_columns: list[str]) -> int:
        # Guard against overwriting the source file when src_path and dst_path point to the same inode.
        if os.path.exists(dst_path) and os.path.samefile(src_path, dst_path):
            raise ValueError("dst_path must be different from src_path")
    
        with open(src_path, "r", encoding="utf-8", newline="") as src_file:
            reader = csv.reader(src_file)
            header = next(reader, None)
            if header is None:
                raise ValueError("source file has no header row")
    
            # Map each required column name to its 0-based index in every CSV row.
            required_positions = []
            for col_name in required_columns:
                if col_name not in header:
                    raise ValueError(f"missing required column: {col_name}")
                required_positions.append(header.index(col_name))
    
            # Place the temp file in dst_path's directory so os.replace stays on the same
            # filesystem and remains a single atomic POSIX directory rename.
            dst_dir = os.path.dirname(os.path.abspath(dst_path))
            tmp_file = tempfile.NamedTemporaryFile(
                "w",
                encoding="utf-8",
                newline="",
                dir=dst_dir,
                prefix=".tmp-",
                suffix=".csv",
                delete=False,
            )
            kept_rows = 0
            try:
                # NamedTemporaryFile defaults to owner-only permissions (0600); widen to 0644.
                os.chmod(tmp_file.name, 0o644)
                with tmp_file:
                    writer = csv.writer(tmp_file)
                    writer.writerow(header)
                    for row in reader:
                        if row_is_valid(row, len(header), required_positions):
                            writer.writerow(row)
                            kept_rows += 1
                    # Flush Python buffers and force OS disk write before publishing via rename.
                    tmp_file.flush()
                    os.fsync(tmp_file.fileno())
                os.replace(tmp_file.name, dst_path)
            except BaseException:
                # Clean up any partial temp file on errors or interrupts; dst_path stays untouched.
                if os.path.exists(tmp_file.name):
                    os.remove(tmp_file.name)
                raise
    
        return kept_rows
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import csv
    import math
    import os
    import tempfile
    
    import numpy as np
    
    
    # ---------- Part 1: atomic, non-destructive CSV cleaning ----------
    
    def is_finite_float(text: str) -> bool:
        """Return True if text parses as a finite float (rejecting '', 'NaN', 'inf', 'abc')."""
        try:
            value = float(text)
        except ValueError:
            return False
        return math.isfinite(value)
    
    
    def row_is_valid(row: List[str], expected_width: int, required_positions: List[int]) -> bool:
        """Keep a row only if its column count matches the header and required cells are finite floats."""
        if len(row) != expected_width:
            return False
        for pos in required_positions:
            if not is_finite_float(row[pos]):
                return False
        return True
    
    
    def sanitize_dataset(src_path: str, dst_path: str, required_columns: list[str]) -> int:
        # Guard against overwriting the source file when src_path and dst_path point to the same inode.
        if os.path.exists(dst_path) and os.path.samefile(src_path, dst_path):
            raise ValueError("dst_path must be different from src_path")
    
        with open(src_path, "r", encoding="utf-8", newline="") as src_file:
            reader = csv.reader(src_file)
            header = next(reader, None)
            if header is None:
                raise ValueError("source file has no header row")
    
            # Map each required column name to its 0-based index in every CSV row.
            required_positions = []
            for col_name in required_columns:
                if col_name not in header:
                    raise ValueError(f"missing required column: {col_name}")
                required_positions.append(header.index(col_name))
    
            # Place the temp file in dst_path's directory so os.replace stays on the same
            # filesystem and remains a single atomic POSIX directory rename.
            dst_dir = os.path.dirname(os.path.abspath(dst_path))
            tmp_file = tempfile.NamedTemporaryFile(
                "w",
                encoding="utf-8",
                newline="",
                dir=dst_dir,
                prefix=".tmp-",
                suffix=".csv",
                delete=False,
            )
            kept_rows = 0
            try:
                # NamedTemporaryFile defaults to owner-only permissions (0600); widen to 0644.
                os.chmod(tmp_file.name, 0o644)
                with tmp_file:
                    writer = csv.writer(tmp_file)
                    writer.writerow(header)
                    for row in reader:
                        if row_is_valid(row, len(header), required_positions):
                            writer.writerow(row)
                            kept_rows += 1
                    # Flush Python buffers and force OS disk write before publishing via rename.
                    tmp_file.flush()
                    os.fsync(tmp_file.fileno())
                os.replace(tmp_file.name, dst_path)
            except BaseException:
                # Clean up any partial temp file on errors or interrupts; dst_path stays untouched.
                if os.path.exists(tmp_file.name):
                    os.remove(tmp_file.name)
                raise
    
        return kept_rows
    
    
    # ---------- Part 2: greedy collinearity filter ----------
    
    def column_values(rows: List[Dict[str, float]], col_name: str) -> List[float]:
        """Extract one named column from row dictionaries as a list of floats."""
        values = []
        for row in rows:
            values.append(float(row[col_name]))
        return values
    
    
    def is_constant(values: List[float]) -> bool:
        """Exact zero-variance check without floating-point mean rounding errors."""
        return min(values) == max(values)
    
    
    def select_uncorrelated_features(rows: List[Dict[str, float]], target_col: str, collinearity_threshold: float = 0.85) -> List[str]:
        if not rows:
            return []
    
        target_values = column_values(rows, target_col)
        if is_constant(target_values):
            # Pearson correlation divides by standard deviation, so a constant target has none.
            return []
    
        # Phase 1: collect non-constant candidate features into a 2D series table.
        # all_series[0] is target_values; all_series[i + 1] corresponds to candidate_names[i].
        candidate_names = []
        all_series = [target_values]
        for col_name in rows[0]:
            if col_name == target_col:
                continue
            values = column_values(rows, col_name)
            if not is_constant(values):
                candidate_names.append(col_name)
                all_series.append(values)
    
        if not candidate_names:
            return []
    
        # Phase 2: compute the (K + 1) x (K + 1) |Pearson correlation| matrix once upfront.
        # Rounding to 12 decimals strips ~1e-16 float noise so mathematically equal |r| values
        # tie cleanly by column name and |r| == 1.0 never slips under threshold 1.0 as 0.9999999999999999.
        abs_corr_matrix = np.round(np.abs(np.corrcoef(np.array(all_series))), 12)
    
        # Phase 3: rank candidates by descending |corr with target|, breaking ties alphabetically.
        # Negating target_corr lets a single ascending tuple sort handle both rules at once.
        ranked_candidates = []
        for idx, col_name in enumerate(candidate_names):
            matrix_idx = idx + 1
            target_corr = float(abs_corr_matrix[0, matrix_idx])
            ranked_candidates.append((-target_corr, col_name, matrix_idx))
        ranked_candidates.sort()
    
        # Phase 4: greedily keep a candidate only if its |corr| with EVERY already-selected
        # feature is strictly less than collinearity_threshold (so >= disqualifies it).
        selected_names = []
        selected_indices = []
        for _, col_name, candidate_idx in ranked_candidates:
            is_redundant = False
            for selected_idx in selected_indices:
                if abs_corr_matrix[candidate_idx, selected_idx] >= collinearity_threshold:
                    is_redundant = True
                    break
            if not is_redundant:
                selected_names.append(col_name)
                selected_indices.append(candidate_idx)
    
        return selected_names
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of select_uncorrelated_features as hiring analysts for a forecasting committee: you score every applicant by Pearson correlation (a number from -1 to +1 measuring how closely two numeric variables track a straight line) with the outcome target_col, hire the strongest predictor first, and skip any later applicant who is a near-clone of someone already on the committee — preventing multicollinearity (when two or more input features carry nearly the same linear signal, destabilizing regression weights). Similarly, think of sanitize_dataset as replacing a live reference manual on a shared shelf using an atomic write (an all-or-nothing file update): you draft and proofread the clean copy into a sibling temporary file, flush it to disk, and swap it into place with a single os.replace rename so readers never see a half-written file.

Naive implementations stumble on both tasks. Opening dst_path directly with "w" immediately truncates any existing file, so a crash mid-way destroys the old output and leaves corrupted CSV lines behind. In feature screening, recomputing correlations from raw rows inside the greedy loop wastes O(N) work per check, and forgetting to strip constant columns or tiny floating-point rounding noise (0.9999999999999999 vs 1.0) breaks ties randomly and lets duplicate columns slip past threshold = 1.0.

Walk through Example 1 (price = [10, 20, 30, 40], sqft = [1, 2, 3, 4], rooms = [2, 4, 5, 9], age = [8, 2, 6, 0], threshold = 0.85):

  1. Upfront |r| with price: sqft has 1.0, rooms has 0.9648, and age has 0.7071 (r = -0.7071), giving rank order ['sqft', 'rooms', 'age'].
  2. sqft is first, so it joins selected_names = ['sqft'].
  3. rooms has |r(rooms, sqft)| = 0.9648 >= 0.85, so it is discarded; age is then checked only against sqft (0.7071 < 0.85) and kept, returning ['sqft', 'age'].

Complexity

Let N be the number of rows and M be the number of candidate feature columns (K <= M non-constant features).

  • Feature selection time: O(N * M^2), because extracting columns and checking min == max scans all N * M cells once (O(N * M)), np.corrcoef multiplies a (K + 1) x N matrix by its transpose in O(N * K^2) (<= O(N * M^2)), sorting K candidates takes O(M log M), and the greedy pass performs at most K * (K - 1) / 2 O(1) matrix lookups (O(M^2)).
  • Feature selection space: O(N * M + M^2), because all_series holds up to (M + 1) * N floats and abs_corr_matrix holds (K + 1)^2 floats.
  • File cleaning time: O(B) where B is the byte size of src_path, because csv.reader and csv.writer inspect and write each row once in a single linear pass.
  • File cleaning space: O(L) RAM and O(B) temporary disk where L is the length of a single CSV row, because streaming via csv.reader holds only one row in memory at a time while staging one cleaned copy on dst_path's filesystem.

Edge cases

  • Exact ties in |r| with target_col: broken deterministically in alphabetical (ASCII / Unicode code-point) order via the tuple (-target_corr, col_name, matrix_idx).
  • Strong negative correlations (r = -1.0): np.abs treats -1.0 identically to +1.0 both when ranking against target_col and when blocking redundant pairs.
  • Pairwise |r| equal to collinearity_threshold: rejected via >=, matching the strict requirement |r| < collinearity_threshold.
  • Boundary thresholds 0.0 and 1.0: at 0.0, the top-ranked feature is still added (since selected_indices starts empty) and every subsequent candidate fails |r| >= 0.0; at 1.0, rounding to 12 decimals ensures exact linear copies (|r| = 1.0) are still dropped.
  • Constant target, constant features, or no valid features: constant features (min == max) are skipped before calling np.corrcoef, and an empty table, constant target, or table with zero non-constant features immediately returns [].
  • CSV hazards (NaN, inf, wrong column count, src_path == dst_path): math.isfinite(float(text)) rejects "NaN" and "inf", len(row) != expected_width drops malformed rows, and os.path.samefile raises ValueError before opening any file for writing.

Common mistakes

  • Forgetting np.abs when ranking or filtering: in Example 2, wind = [-3, -1, 1, 3] has r = -1.0 with load = [4, 2, 0, -2]; sorting by signed r puts a perfect predictor dead last.
  • Comparing a candidate against dropped features instead of only selected_indices: if sqft drops rooms, rooms is not in the model and must never block age.
  • Using <= instead of < on collinearity_threshold (or skipping np.round): keeps features sitting right on the threshold, or lets scaled duplicates with float correlation 0.9999999999999999 pass < 1.0.
  • Creating the temp file in /tmp instead of dst_dir: /tmp is frequently a separate tmpfs mount, causing os.replace to fail with EXDEV (Invalid cross-device link).
  • Leaving default 0600 permissions or skipping cleanup on exceptions: NamedTemporaryFile creates owner-only files unless os.chmod is called, and delete=False leaks .tmp-* files on errors unless wrapped in try / except BaseException.

Alternative approaches

  • Using pandas directly: When input arrives as a pd.DataFrame, drop constant columns via df.nunique() > 1, compute abs_corr = df.corr(method="pearson").abs().round(12), and run the exact same greedy loop; for sanitize_dataset, iterate pd.read_csv(src_path, chunksize=50_000) into the same NamedTemporaryFile + os.replace wrapper.
  • On-demand dot products when M is huge and few features survive: Z-score normalize each candidate column once (z = (x - mean) / std, O(N * M) total), sort by |z_target . z_j| / N, and compute pairwise dot products |z_cand . z_sel| / N only against features that actually enter selected_indices, reducing O(N * M^2) to O(N * M * S) when S << M features are selected.

Follow-up questions

  • How would you process multi-gigabyte CSV logs that are far larger than system memory, and how could you parallelize that throughput safely? Our csv.reader / csv.writer implementation already streams one line at a time in O(longest_row) RAM, so a multi-gigabyte file will not exhaust memory as long as dst_dir has enough free disk space for the staged temporary file (whereas pd.read_csv(src_path) without chunksize would crash with MemoryError). To speed up wall-clock throughput, split src_path into byte-offset ranges aligned to newline boundaries (assuming no multi-line quoted strings), validate ranges in parallel worker processes writing separate .tmp-part-k files, concatenate the parts in order into one staged file, fsync, and publish with a single os.replace.
  • What kind of multi-feature redundancy slips past pairwise correlation checks, and how do Variance Inflation Factor (VIF) or Principal Component Analysis (PCA) catch it? Pairwise correlation only inspects two features at a time, so if x1 and x2 are independent standard normals and x3 = x1 + x2, then |corr(x3, x1)| = |corr(x3, x2)| = 1 / sqrt(2) ≈ 0.707 < 0.85 — all three pass the filter even though x3 is a 100% redundant sum of x1 and x2! Variance Inflation Factor (VIF) (defined as 1 / (1 - R_j^2), where R_j^2 is the R^2 from regressing feature j against all other features simultaneously) catches multi-way linear combinations (R_3^2 = 1 gives VIF = infinity), and you iteratively drop the highest-VIF feature until all VIFs sit below 5 or 10. Principal Component Analysis (PCA) (an orthogonal linear transformation that projects correlated features onto uncorrelated axes ordered by variance explained) removes collinearity completely by dropping near-zero-variance components, trading away individual column interpretability.
  • When concurrent workers in a distributed job queue target the same output path, how do you prevent stale overwrites and write races? Unique .tmp-* filenames plus os.replace prevent corrupt interleaved bytes on POSIX filesystems, but two concurrent workers still suffer a "last writer wins" race where a slow retry from an older run overwrites fresher data. If the transformation is idempotent (running it multiple times on the same immutable input produces byte-for-byte identical output), duplicate execution is harmless; otherwise, write each job's output to an immutable versioned path (dst/run_id=.../part-*.parquet) and update a single metadata pointer or transactional table log (such as Delta Lake or Iceberg) using optimistic concurrency control. If you must coordinate a single mutable path across machines, acquire a distributed lock backed by a fencing token (a monotonically increasing integer issued with each lock grant that storage checks to reject stale writes from paused workers).

Follow-up questions

Similar questions

More Voleon interview questions

All 34 Voleon questions →