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
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess 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
Get started

Code Speed Optimization

MediumCoding00:00
Practice interviewer
In session
5 left
00:00

Your question is Code Speed Optimization. Take a moment with it on the right.

Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).

You need to log in / sign up to chat or submit.

Problem

The School of Management del Politecnico di Milano wants a leaderboard tool for advisors: given the whole student roster, pull the top five scorers in a given course. A first draft works on a small pilot cohort but grinds to a crawl on the full multi-thousand-student roster.

def top_scoring_students(students, course_code):
    # students: list of dicts with id, name, and a list of course score records
    results = []
    for student in students:
        for course in student["courses"]:
            if course["code"] == course_code:
                results.append((student["name"], course["score"]))

    sorted_results = []
    for r in results:
        inserted = False
        for i in range(len(sorted_results)):
            if r[1] > sorted_results[i][1]:
                sorted_results.insert(i, r)
                inserted = True
                break
        if not inserted:
            sorted_results.append(r)

    top_five = []
    for i in range(5):
        top_five.append(sorted_results[i])
    return top_five

How would you optimize this for speed? Explain both what makes it slow and what would break on a small elective course, and what you'd do about each.