Count Number of Teams Problem
Description
LeetCode Problem 1395.
There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
- Choose 3 soldiers with index (
i,j,k) with rating (rating[i],rating[j],rating[k]). - A team is valid if: (
rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).
Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
Example 1:
Input: rating = [2,5,3,4,1]
Output: 3
Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).
Example 2:
Input: rating = [2,1,3]
Output: 0
Explanation: We can't form any team given the conditions.
Example 3:
Input: rating = [1,2,3,4]
Output: 4
Constraints:
n == rating.length3 <= n <= 10001 <= rating[i] <= 10^5- All the integers in
ratingare unique.
Solution
Approach: Count Around the Middle Soldier
Checking every triple is O(n3), about 1.7 * 108 triples for n = 1000. Instead, fix the middle soldier j and count how many teams use it in the middle.
Let leftLess be the number of soldiers to the left of j with a smaller rating and rightGreater the number to the right with a larger rating. Every pair of one such left soldier and one such right soldier is an increasing team, which gives leftLess * rightGreater teams. In the same way, decreasing teams number leftGreater * rightLess.
Because all ratings are unique, nothing is equal to rating[j], so the other two counts come for free: leftGreater = j - leftLess and rightLess = (n - 1 - j) - rightGreater.
Sum these two products over all j. In Example 1 ([2,5,3,4,1]), the middle 3 has one smaller on the left (2) and one larger on the right (4), giving (2,3,4), plus one larger on the left (5) and one smaller on the right (1), giving (5,3,1).
The count for each j can also come from a Binary Indexed Tree over the ratings, for O(n log n) overall, but for n <= 1000 the quadratic scan is simple and fast enough.
Complexity: O(n2) time and O(1) extra space.
class Solution:
def numTeams(self, rating: List[int]) -> int:
n = len(rating)
ans = 0
for j in range(1, n - 1): # rating[j] is the middle soldier
mid = rating[j]
left_less = sum(1 for i in range(j) if rating[i] < mid)
right_greater = sum(1 for k in range(j + 1, n) if rating[k] > mid)
left_greater = j - left_less # ratings are unique, so the rest are greater
right_less = n - 1 - j - right_greater
ans += left_less * right_greater + left_greater * right_less
return ans