The Number of Weak Characters in the Game — LeetCode 1996 Python Solution

MediumStackGreedyArraySortingMonotonic Stack
Problem
#1996
Pattern
Stack
Reading time
2 min

The 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.

Example

Input
properties = [[5,5],[6,3],[3,6]]
Output
0
Explanation
No character has strictly greater attack and defense than the other.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1996. The Number of Weak Characters in the Game is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1996. The Number of Weak Characters in the Game?
LeetCode 1996. The Number of Weak Characters in the Game is rated Medium on LeetCode.
What is the time complexity of LeetCode 1996. The Number of Weak Characters in the Game?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1996. The Number of Weak Characters in the Game?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1996. The Number of Weak Characters in the Game cover?
LeetCode 1996. The Number of Weak Characters in the Game is tagged Stack, Greedy, Array, Sorting and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview