#2512

Reward Top K Students

Medium
ArrayHash TableStringSortingHeap (Priority Queue)Hash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(n)

In this approach, we use a hash map to store scores efficiently while iterating through the reports only once. This reduces the time complexity significantly, allowing us to handle larger inputs.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a hash map to store scores for each student.
  2. 2Step 2: Create sets for positive and negative feedback for O(1) lookups.
  3. 3Step 3: Iterate through each report, split the words, and update the scores using the hash map.
  4. 4Step 4: Sort the students based on their scores and IDs using a custom comparator.
  5. 5Step 5: Return the top k students.
solution.py15 lines
1def topKStudents(positive_feedback, negative_feedback, report, student_id, k):
2    score = {}
3    pos_set = set(positive_feedback)
4    neg_set = set(negative_feedback)
5    for i in range(len(report)):
6        words = report[i].split()
7        student = student_id[i]
8        score[student] = score.get(student, 0)
9        for word in words:
10            if word in pos_set:
11                score[student] += 3
12            elif word in neg_set:
13                score[student] -= 1
14    sorted_students = sorted(score.items(), key=lambda x: (-x[1], x[0]))
15    return [student for student, _ in sorted_students[:k]]

Complexity note: The time complexity is O(n log n) due to the sorting step after calculating the scores, while the space complexity is O(n) for storing the scores in a hash map.

  • 1Using hash maps allows for efficient score tracking and retrieval.
  • 2Sorting based on multiple criteria (score and ID) is a common pattern in ranking problems.

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