Reward Top K Students — LeetCode 2512 Python Solution

MediumArrayHash TableStringSortingHeap (Priority Queue)
Problem
#2512
Reading time
4 min

The problem

You are given two string arrays positive_feedback and negative_feedback, containing the words denoting positive and negative feedback, respectively. Note that no word is both positive and negative.

Example

Input
positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is studious","the student is smart"], student_id = [1,2], k = 2
Output
[1,2]
Explanation
Both the students have 1 positive feedback and 3 points but since student 1 has a lower ID he ranks higher.

Python solution

Python
class Solution:
    def topStudents(
        self,
        positive_feedback: List[str],
        negative_feedback: List[str],
        report: List[str],
        student_id: List[int],
        k: int,
    ) -> List[int]:
        ps = set(positive_feedback)
        ns = set(negative_feedback)
        arr = []
        for sid, r in zip(student_id, report):
            t = 0
            for w in r.split():
                if w in ps:
                    t += 3
                elif w in ns:
                    t -= 1
            arr.append((t, sid))
        arr.sort(key=lambda x: (-x[0], x[1]))
        return [v[1] for v in arr[:k]]

Complexity

MeasureComplexity
TimeO(n \times \log n + (|ps| + |ns| + n) \times |s|)
SpaceO((|ps|+|ns|) \times |s| + n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2512. Reward Top K Students is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2512. Reward Top K Students?
LeetCode 2512. Reward Top K Students is rated Medium on LeetCode.
What is the time complexity of LeetCode 2512. Reward Top K Students?
The Python solution on this page runs in O(n \times \log n + (|ps| + |ns| + n) \times |s|).
What is the space complexity of LeetCode 2512. Reward Top K Students?
The Python solution on this page uses O((|ps|+|ns|) \times |s| + n) auxiliary space.
What topics does LeetCode 2512. Reward Top K Students cover?
LeetCode 2512. Reward Top K Students is tagged Array, Hash Table, String, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview