#2512
Medium Algorithms Reward top k students
Array Hash Table String Sorting Heap (Priority Queue)
46.8% acceptance
Feb 25, 2026
361
92
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.
Initially every student has 0 points. Each positive word in a feedback report increases
the points of a student by 3, whereas each negative word decreases the points by 1.
You are given n feedback reports, represented by a 0-indexed string array report and
a 0-indexed integer array student_id, where student_id[i] represents the ID of the student
who has received the feedback report report[i]. The ID of each student is unique.
Given an integer k, return the top k students after ranking them in non-increasing order
by their points. In case more than one student has the same points, the one with the lower
ID ranks higher.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn top_students(
positive_feedback: Vec<String>,
negative_feedback: Vec<String>,
report: Vec<String>,
student_id: Vec<i32>,
k: i32,
) -> Vec<i32> {
use std::collections::HashSet;
let pos: HashSet<&str> = positive_feedback.iter().map(|s| s.as_str()).collect();
let neg: HashSet<&str> = negative_feedback.iter().map(|s| s.as_str()).collect();
let mut scores: Vec<(i32, i32)> = student_id
.iter()
.zip(report.iter())
.map(|(&id, rep)| {
let score = rep
.split_whitespace()
.map(|w| {
if pos.contains(w) {
3
} else if neg.contains(w) {
-1
} else {
0
}
})
.sum::<i32>();
(-score, id)
})
.collect();
scores.sort_unstable();
scores.iter().take(k as usize).map(|&(_, id)| id).collect()
}
}