Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1996.html

1996. The Number of Weak Characters in the Game

Level

Medium

Description

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] = [attack_i, defense_i] represents the properties of the i-th character in the game.

A character is said to be weak if any other character has both attack and defense levels strictly greater than this character’s attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attack_j > attack_i and defense_j > defense_i.

Return the number of weak characters.

Example 1:

Input: properties = [[5,5],[6,3],[3,6]]

Output: 0

Explanation: No character has strictly greater attack and defense than the other.

Example 2:

Input: properties = [[2,2],[3,3]]

Output: 1

Explanation: The first character is weak because the second character has a strictly greater attack and defense.

Example 3:

Input: properties = [[1,5],[10,4],[4,3]]

Output: 1

Explanation: The third character is weak because the second character has a strictly greater attack and defense.

Constraints:

  • 2 <= properties.length <= 10^5
  • properties[i].length == 2
  • 1 <= attack_i, defense_i <= 10^5

Solution

Sort properties according to attack in ascending order and then according to defense in ascending order. Loop over properties backwards. When a character is visited, the characters with greater attack values have already been visited. If there exists at least one character among these characters that has a greater defense value, then the current character is weak.

  • class Solution {
        public int numberOfWeakCharacters(int[][] properties) {
            Arrays.sort(properties, new Comparator<int[]>() {
                public int compare(int[] property1, int[] property2) {
                    if (property1[0] != property2[0])
                        return property1[0] - property2[0];
                    else
                        return property1[1] - property2[1];
                }
            });
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int[] property : properties) {
                int attack = property[0], defense = property[1];
                if (defense > map.getOrDefault(attack, 0))
                    map.put(attack, defense);
            }
            int count = 0;
            int length = properties.length;
            int index = length - 2;
            while (index >= 0 && properties[index][0] == properties[index + 1][0])
                index--;
            if (index < 0)
                return 0;
            int maxDefense = properties[length - 1][1];
            for (int i = index; i >= 0; i--) {
                int attack = properties[i][0], defense = properties[i][1];
                if (defense < maxDefense)
                    count++;
                if (i > 0 && attack > properties[i - 1][0]) {
                    int curMaxDefense = map.get(attack);
                    maxDefense = Math.max(maxDefense, curMaxDefense);
                }
            }
            return count;
        }
    }
    
    ############
    
    class Solution {
        public int numberOfWeakCharacters(int[][] properties) {
            Arrays.sort(properties, (a, b) -> b[0] - a[0] == 0 ? a[1] - b[1] : b[0] - a[0]);
            int ans = 0, mx = 0;
            for (var x : properties) {
                if (x[1] < mx) {
                    ++ans;
                }
                mx = Math.max(mx, x[1]);
            }
            return ans;
        }
    }
    
  • // OJ: https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/
    // Time: O(NlogN)
    // Space: O(N)
    class Solution {
    public:
        int numberOfWeakCharacters(vector<vector<int>>& A) {
            sort(begin(A), end(A), [](auto &a, auto &b) { return a[0] < b[0]; });
            multiset<int> s;
            for (auto &a : A) s.insert(a[1]);
            int N = A.size(), ans = 0;
            for (int i = 0; i < N; ) {
                vector<int> ds;
                int at = A[i][0];
                while (i < N && A[i][0] == at) {
                    ds.push_back(A[i][1]);
                    s.erase(s.find(A[i][1]));
                    ++i;
                }
                for (int d : ds) {
                    ans += s.upper_bound(d) != s.end();
                }
            }
            return ans;
        }
    };
    
  • class Solution:
        def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
            properties.sort(key=lambda x: (-x[0], x[1]))
            ans = mx = 0
            for _, d in properties:
                if mx > d:
                    ans += 1
                mx = max(mx, d)
            return ans
    
    ############
    
    # 1996. The Number of Weak Characters in the Game
    # https://leetcode.com/problems/the-number-of-weak-characters-in-the-game
    
    class Solution:
        def numberOfWeakCharacters(self, A: List[List[int]]) -> int:
            A.sort(key = lambda x:(x[0], -x[1]))
            stack = []
            res = 0
            
            for a,b in A:
                while stack and a > stack[-1][0] and b > stack[-1][1]:
                    stack.pop()
                    res += 1
                
                stack.append((a, b))
            
            return res
    
    
  • func numberOfWeakCharacters(properties [][]int) (ans int) {
    	sort.Slice(properties, func(i, j int) bool {
    		a, b := properties[i], properties[j]
    		if a[0] == b[0] {
    			return a[1] < b[1]
    		}
    		return a[0] > b[0]
    	})
    	mx := 0
    	for _, x := range properties {
    		if x[1] < mx {
    			ans++
    		} else {
    			mx = x[1]
    		}
    	}
    	return
    }
    
  • function numberOfWeakCharacters(properties: number[][]): number {
        properties.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]));
        let ans = 0;
        let mx = 0;
        for (const [, x] of properties) {
            if (x < mx) {
                ans++;
            } else {
                mx = x;
            }
        }
        return ans;
    }
    
    
  • /**
     * @param {number[][]} properties
     * @return {number}
     */
    var numberOfWeakCharacters = function (properties) {
        properties.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]));
        let ans = 0;
        let mx = 0;
        for (const [, x] of properties) {
            if (x < mx) {
                ans++;
            } else {
                mx = x;
            }
        }
        return ans;
    };
    
    

All Problems

All Solutions