Karat / VO OA Interview Question: Find Shared Courses for Every Pair of Students

17 Views
No Comments

You are a developer for a university. Your current project is to develop a system for students to find courses they share with friends.

The university has a system for querying courses students are enrolled in, returned as a list of (student ID, course) pairs.

Write a function that takes in a collection of (student ID number, course name) pairs and returns, for every pair of students, a collection of all courses they share.

Sample Input:

enrollments1 = [["58", "Linear Algebra"],
  ["94", "Art History"],
  ["94", "Operating Systems"],
  ["17", "Software Design"],
  ["58", "Mechanics"],
  ["58", "Economics"],
  ["17", "Linear Algebra"],
  ["17", "Political Science"],
  ["94", "Economics"],
  ["25", "Economics"],
  ["58", "Software Design"],
]

Sample Output (pseudocode, in any order):

find_pairs(enrollments1) =>
{"58,17": ["Software Design", "Linear Algebra"],
  "58,94": ["Economics"],
  "58,25": ["Economics"],
  "94,25": ["Economics"],
  "17,94": [],
  "17,25": []}

This problem is best solved in two steps: first build a hash map from each student to the set of courses they take, then compute the intersection for every pair of students. A set-based approach makes it easy to deduplicate courses and check overlaps efficiently. After grouping enrollments, iterate over all student pairs and return the shared-course list for each pair, preserving the sample’s pairwise output format.

END
 0