Problem Description
Given an array of characters represented by their attack and defense properties, determine the number of characters that are "weak." A character is weak if there exists another character with both a strictly greater attack and a strictly greater defense property.
Key Insights
- Sort the characters in descending order by attack. For characters with the same attack value, sort them in ascending order by defense.
- Iterate through the sorted list while tracking the maximum defense seen so far.
- A character is weak if its defense is less than the current maximum defense.
- Sorting by attack in descending order ensures that when comparing, no future character has a higher attack.
- Sorting by defense in ascending order (for equal attack values) prevents incorrectly marking characters as weak when their attack values are the same.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the array. Space Complexity: O(n) for the space used by the sorting algorithm (depending on the language implementation) and additional variables.
Solution
The solution leverages a greedy sorting approach:
- Sort the characters such that characters with higher attack come first, and if attacks are equal, order them by increasing defense.
- Initialize a variable, maxDefense, to 0. This variable keeps track of the highest defense value encountered while iterating.
- Iterate through the sorted array and for each character:
- If the current character's defense is less than maxDefense, it is weak because a character with a higher attack (due to sorting) and a higher defense exists.
- Otherwise, update maxDefense with the current character's defense. This process ensures each character is checked exactly once following the sorted order, thus meeting the required performance constraints.