Karat / VO 面试真题解析:找出任意两位学生共享的课程

18次阅读
没有评论

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": []}

这道题的核心是先把“学生 → 课程集合”建出来,再枚举每一对学生,求两个集合的交集。因为输入是若干条学生选课记录,最自然的做法是用哈希表把每个 student ID 映射到其课程集合,这样可以快速判断两位学生是否共享课程。随后对所有学生两两组合,使用集合交集或遍历较小集合来计算共同课程,并按题目要求返回每一对学生对应的结果。样例中 58 和 17 共享“Software Design”与“Linear Algebra”,58 和 94 共享“Economics”,而 17 和 94 没有共同课程。

正文完
 0