The Number of Weak Characters in the Game

medium array stack greedy sorting monotonic stack

Problem

A character is weak if some other character has strictly greater attack and strictly greater defense. Return the number of weak characters.

Inputproperties = [[5,5],[6,3],[3,6]]
Output0
No one dominates another in both dimensions strictly.

def number_of_weak_characters(properties):
    properties.sort(key=lambda p: (-p[0], p[1]))
    weak = 0
    max_def = 0
    for _, d in properties:
        if d < max_def:
            weak += 1
        else:
            max_def = d
    return weak
function numberOfWeakCharacters(properties) {
  properties.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : b[0] - a[0]);
  let weak = 0, maxDef = 0;
  for (const [, d] of properties) {
    if (d < maxDef) weak++;
    else maxDef = d;
  }
  return weak;
}
class Solution {
    public int numberOfWeakCharacters(int[][] properties) {
        Arrays.sort(properties, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
        int weak = 0, maxDef = 0;
        for (int[] p : properties) {
            if (p[1] < maxDef) weak++;
            else maxDef = p[1];
        }
        return weak;
    }
}
int numberOfWeakCharacters(vector<vector<int>>& properties) {
    sort(properties.begin(), properties.end(), [](auto& a, auto& b) {
        return a[0] == b[0] ? a[1] < b[1] : a[0] > b[0];
    });
    int weak = 0, maxDef = 0;
    for (auto& p : properties) {
        if (p[1] < maxDef) weak++;
        else maxDef = p[1];
    }
    return weak;
}
Time: O(n log n) Space: O(1)