The Number of Weak Characters in the Game - Problem

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] = [attacki, defensei] represents the properties of the ith 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 attackj > attacki and defensej > defensei.

Return the number of weak characters.

Input & Output

Example 1 — Mixed Characters
$ Input: properties = [[5,5],[6,3],[2,4],[1,6]]
Output: 1
💡 Note: Character [2,4] is weak because [5,5] has both higher attack (5>2) and higher defense (5>4). All other characters are not dominated by any single character.
Example 2 — All Strong Characters
$ Input: properties = [[2,2],[3,3]]
Output: 1
💡 Note: Character [2,2] is weak because [3,3] has both higher attack (3>2) and higher defense (3>2). Character [3,3] is not weak.
Example 3 — No Weak Characters
$ Input: properties = [[1,5],[10,4],[4,3]]
Output: 0
💡 Note: No character dominates any other in both attack AND defense: [1,5] has highest defense, [10,4] has highest attack, [4,3] is not dominated by either.

Constraints

  • 2 ≤ properties.length ≤ 105
  • properties[i].length == 2
  • 1 ≤ attacki, defensei ≤ 105

Visualization

Tap to expand
Weak Characters in Game INPUT Characters [attack, defense]: [5, 5] Char 0 [6, 3] Char 1 [2, 4] Char 2 WEAK! [1, 6] Char 3 Attack vs Defense Grid: Attack --> Defense (5,5) (6,3) (2,4) (1,6) ALGORITHM STEPS 1 Sort by Attack DESC If same attack, sort defense ASC [6,3] [5,5] [2,4] [1,6] 2 Track Max Defense Iterate and track maxDef seen 3 Compare Each Char If defense < maxDef, char is weak Char maxDef Weak? [6,3] 3 No [5,5] 5 No [2,4] 5 Yes (4<5) 4 Count Weak Chars Return total count = 1 FINAL RESULT Output: 1 One weak character found Why [2,4] is weak? Character [5,5] dominates: Attack: 5 > 2 OK Defense: 5 > 4 OK Other chars NOT weak: [5,5]: No one beats both [6,3]: Has max attack [1,6]: Has max defense Key Insight: By sorting attacks in descending order (with same attacks sorted by defense ascending), we ensure that when we process each character, all characters with higher attack come first. We only need to track the maximum defense seen so far. Time: O(n log n), Space: O(1). TutorialsPoint - The Number of Weak Characters in the Game | Optimal Solution
Asked in
Amazon 45 Google 38 Microsoft 32 Apple 28
67.6K Views
Medium-High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen