Sort Threats by Severity and Exploitability Problem
#3631
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3631.
You are given a 2D integer array threats, where each threats[i] = [ID_i, sev_i, exp_i]
ID_i: Unique identifier of the threat.sev_i: Indicates the severity of the threat.exp_i: Indicates the exploitability of the threat.
The score of a threat i is defined as: score = 2 × sev_i + exp_i
Your task is to return threats sorted in descending order of score.
If multiple threats have the same score, sort them by ascending ID.
Example 1:
Input: threats = [[101,2,3],[102,3,2],[103,3,3]]
Output: [[103,3,3],[102,3,2],[101,2,3]]
Explanation:
Threat ID sev exp Score = 2 × sev + exp
threats[0] 101 2 3 2 × 2 + 3 = 7
threats[1] 102 3 2 2 × 3 + 2 = 8
threats[2] 103 3 3 2 × 3 + 3 = 9
Sorted Order: [[103, 3, 3], [102, 3, 2], [101, 2, 3]]
Example 2:
Input: threats = [[101,4,1],[103,1,5],[102,1,5]]
Output: [[101,4,1],[102,1,5],[103,1,5]]
Explanation:
Threat ID sev exp Score = 2 × sev + exp
threats[0] 101 4 1 2 × 4 + 1 = 9
threats[1] 103 1 5 2 × 1 + 5 = 7
threats[2] 102 1 5 2 × 1 + 5 = 7
threats[1] and threats[2] have same score, thus sort them by ascending ID.
Sorted Order: [[101, 4, 1], [102, 1, 5], [103, 1, 5]]
Constraints:
1 <= threats.length <= 10^5threats[i] == [ID_i, sev_i, exp_i]1 <= ID_i <= 10^61 <= sev_i <= 10^91 <= exp_i <= 10^9- All
ID_iare unique
Solution
Approach: Sorting
Sort the threats with a custom comparator: higher score 2 * sev + exp first, and the smaller ID first when the scores are equal. The score can reach 3 * 10^9, which does not fit in a 32-bit integer, so compute it with 64-bit integers.
Complexity: O(n log n) time and O(log n) space, where n is the number of threats.
class Solution:
def sortThreats(self, threats: List[List[int]]) -> List[List[int]]:
threats.sort(key=lambda x: (-(x[1] * 2 + x[2]), x[0]))
return threats