Leetcode 1996: The Number of Weak Characters in the Game

grid47
grid47
Exploring patterns and algorithms
Apr 21, 2024 5 min read

You are given a list of characters’ properties, where each character has two main attributes: attack and defense. A character is weak if another character exists with both greater attack and defense values. Return the number of weak characters in the list.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D array 'properties' of length n (2 <= n <= 100,000), where each element is an array [attack_i, defense_i] representing the attack and defense values of the ith character.
Example: properties = [[1, 2], [2, 1], [3, 4]]
Constraints:
• 2 <= properties.length <= 10^5
• 1 <= attack_i, defense_i <= 10^5
Output: Return the number of weak characters in the list.
Example: 1
Constraints:
Goal: We need to find the weak characters by comparing each character with others to check if there exists a character with strictly greater attack and defense values.
Steps:
• 1. Sort the characters by their attack value in ascending order. If two characters have the same attack value, sort them by their defense value in descending order.
• 2. Traverse through the sorted list and keep track of the highest defense value encountered.
• 3. If a character's defense value is smaller than the highest defense value encountered so far, it is a weak character.
• 4. Count and return the number of weak characters.
Goal: The constraints ensure the problem is solvable within time limits for large inputs.
Steps:
• The input array has between 2 and 100,000 elements.
• Each attack and defense value is between 1 and 100,000.
Assumptions:
• All characters have distinct attack and defense values.
Input: properties = [[3, 5], [6, 3], [7, 8], [4, 7]]
Explanation: Here, the character [3, 5] is weak because there exists a character [6, 3] with strictly greater attack and defense values.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus