The Number of Weak Characters in the Game Problem
Description
LeetCode Problem 1996.
You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attack_i, defense_i] represents the properties of the i^th character in the game.
A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attack_j > attack_i and defense_j > defense_i.
Return the number of weak characters.
Example 1:
Input: properties = [[5,5],[6,3],[3,6]]
Output: 0
Explanation: No character has strictly greater attack and defense than the other.
Example 2:
Input: properties = [[2,2],[3,3]]
Output: 1
Explanation: The first character is weak because the second character has a strictly greater attack and defense.
Example 3:
Input: properties = [[1,5],[10,4],[4,3]]
Output: 1
Explanation: The third character is weak because the second character has a strictly greater attack and defense.
Constraints:
2 <= properties.length <= 10^5properties[i].length == 21 <= attack_i, defense_i <= 10^5
Solution
Approach: Sort by Attack, Then Scan
A character is weak if some other character has both higher attack and higher defense. Sort the characters by attack in descending order and, for equal attack, by defense in ascending order.
Walk through the sorted list while keeping mx, the largest defense seen so far. Every character seen before the current one has attack at least as high. If the attack is strictly higher, the current character is weak when its defense is below mx. The tie-break handles equal attack: within a group of equal attack, defense is ascending, so a character in the same group never has a larger defense in front of it and mx only comes from strictly higher attack. So:
- if the defense is less than
mx, the character is weak, so add one to the answer; - otherwise update
mx.
Complexity: O(n log n) time for the sort and O(log n) extra space.
class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
properties.sort(key=lambda x: (-x[0], x[1]))
ans = mx = 0
for _, x in properties:
ans += x < mx
mx = max(mx, x)
return ans