#1996
The Number of Weak Characters in the Game
MediumArrayStackGreedySortingMonotonic StackSortingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the characters based on their attack values and using a single pass to track the maximum defense seen so far, we can efficiently determine the number of weak characters.
⚙️
Algorithm
5 steps- 1Step 1: Sort the characters by attack in ascending order. If attacks are equal, sort by defense in descending order.
- 2Step 2: Initialize a variable to keep track of the maximum defense encountered so far.
- 3Step 3: Iterate through the sorted list and for each character, check if its defense is less than the maximum defense seen so far.
- 4Step 4: If it is, increment the weak character count.
- 5Step 5: Update the maximum defense with the current character's defense if it's greater.
solution.py14 lines
1# Full working Python code
2properties = [[5,5],[6,3],[3,6]]
3
4def countWeakCharacters(properties):
5 properties.sort(key=lambda x: (x[0], -x[1]))
6 weak_count = 0
7 max_defense = 0
8 for attack, defense in properties:
9 if defense < max_defense:
10 weak_count += 1
11 max_defense = max(max_defense, defense)
12 return weak_count
13
14print(countWeakCharacters(properties))ℹ
Complexity note: The sorting step dominates the time complexity, making it O(n log n). The subsequent single pass through the list is O(n).
- 1Sorting helps in efficiently grouping characters by attack values.
- 2Using a single pass after sorting allows us to leverage previously seen defenses.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.