← 返回 walmartlabs 的题目列表Course Overlap by Student ID
类型:qbank
Given a list of `(student_id, course_name)` pairs, output for every unordered pair of distinct students the list of courses they both take. The output keys are formatted as the two student IDs joined by a comma.
Requirements
Input: String[][] course — each entry is [student_id, course_name].
Build a mapping studentId → Set<course>.
For every unordered pair of distinct students, output the intersection of their course sets. Include pairs with empty intersection.
Output key is "smaller_id,larger_id"; value is a List<String> of overlapping courses (any deterministic order is acceptable, but be ready to discuss).
Examples
Input:
[["17","Math"], ["17","English"], ["58","Math"], ["61","Physics"]]
Output:
"17,58" → ["Math"]
"17,61" → []
"58,61" → []
Notes
O(s²) over the student set is acceptable for the sizes the interviewer ships — premature optimization to inverted indexes is usually unnecessary unless the prompt scales the student count explicitly.
For the intersection step, iterate the smaller of the two course sets and probe the larger; this is meaningfully faster than retainAll on Java HashSet when one side is much smaller.
Sort student IDs lexicographically before composing the key so "17,58" and "58,17" collapse to a single entry. Numeric-string sort vs. integer sort is a clarifying question worth asking — the reported variant used string IDs and lexicographic order matched the expected output.
If the interviewer scales the input (millions of records), pivot to an inverted index course → Set<student> and emit pairs only for courses with |students| ≥ 2. This avoids the s² blow-up when most student pairs share no courses.
Preparation
Walk through the input → student-map → pairwise-intersection pipeline on a 4-student / 3-course example before coding; it shortens the verbal explanation to under a minute.
Practice the inverted-index follow-up since the interviewer often pushes for it after the brute-force passes. Estimate the cost as Σ_c (|students(c)| choose 2) and discuss when it beats s².
Cover the two edge cases the round flagged: students with no courses (must still appear in pairs with []) and duplicate (student, course) rows (dedupe per student first).