#3764

Most Common Course Pairs

Hard
Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use a hash map to efficiently count course pairs as we iterate through the course sequences of top-performing students, reducing the need for nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Filter top-performing students and store their course sequences.
  2. 2Step 2: Use a hash map to count occurrences of each course pair as we traverse each student's course list.
  3. 3Step 3: Return the pairs sorted by frequency.
solution.py1 lines
1SELECT course_a, course_b, COUNT(*) as pair_freq FROM (SELECT user_id, course_id as course_a, LEAD(course_id) OVER (PARTITION BY user_id ORDER BY completion_date) as course_b FROM course_completions WHERE user_id IN (SELECT user_id FROM course_completions GROUP BY user_id HAVING COUNT(*) >= 5 AND AVG(course_rating) >= 4)) AS pairs GROUP BY course_a, course_b ORDER BY pair_freq DESC;

Complexity note: The optimal approach leverages a single pass through the data to count pairs, leading to linear time complexity.

  • 1Focus on top performers to identify effective learning paths.
  • 2Course sequences can reveal valuable insights into skill progression.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.