Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Refactor for Performance and Clarity
00:00
5 left

Refactor for Performance and Clarity

HardPython

Problem

A quant on the desk wrote this code to build a pairwise correlation matrix across a basket of tickers' daily return series, so it can feed into a portfolio risk model. It's correct on the small baskets used in backtests, but on the full universe of a few hundred tickers with years of daily returns it's become too slow to run intraday.

double computeCorrelation(std::vector<double> a, std::vector<double> b) {
    double sumA = 0, sumB = 0;
    for (int i = 0; i < a.size(); i++) {
        sumA += a[i];
        sumB += b[i];
    }
    double meanA = sumA / a.size();
    double meanB = sumB / b.size();

    double cov = 0, varA = 0, varB = 0;
    for (int i = 0; i < a.size(); i++) {
        cov += (a[i] - meanA) * (b[i] - meanB);
        varA += (a[i] - meanA) * (a[i] - meanA);
        varB += (b[i] - meanB) * (b[i] - meanB);
    }

    return cov / sqrt(varA * varB);
}

std::vector<std::vector<double>> buildCorrelationMatrix(std::vector<std::vector<double>> returns) {
    std::vector<std::vector<double>> matrix;
    for (int i = 0; i < returns.size(); i++) {
        std::vector<double> row;
        for (int j = 0; j < returns.size(); j++) {
            row.push_back(computeCorrelation(returns[i], returns[j]));
        }
        matrix.push_back(row);
    }
    return matrix;
}

Refactor this for performance while keeping it correct. Explain exactly what makes the current version slow and what could go wrong with it beyond just speed, before proposing your changes.

Implement correlation_matrix(returns), where returns is a nonempty list of equal-length numeric series. Return a square list of floating-point correlations. Treat a zero-variance series as having correlation 0.0 with every series, including itself.

Constraints

  • 1 <= len(returns) <= 500
  • 1 <= len(returns[i]) <= 5000
  • All series have the same positive length
  • Each value is a finite integer or floating-point number
  • A zero-variance series must produce 0.0 correlations

Function Signature

def correlation_matrix(returns):
Interviewer

Your question is Refactor for Performance and Clarity. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.