Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
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.