#1395

Count Number of Teams

Medium
ArrayDynamic ProgrammingBinary Indexed TreeSegment TreeCombination CountingDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal approach leverages counting how many soldiers have a lower or higher rating than the current soldier at index j. This way, we can efficiently calculate valid teams without checking every combination.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter to zero to keep track of valid teams.
  2. 2Step 2: For each soldier at index j, count how many soldiers before it have a lower rating and how many have a higher rating.
  3. 3Step 3: For each soldier at index j, count how many soldiers after it have a lower rating and how many have a higher rating.
  4. 4Step 4: Multiply the counts from Step 2 and Step 3 to get the number of valid teams for that soldier as the middle member.
  5. 5Step 5: Sum the results for all soldiers to get the total count.
solution.py15 lines
1# Full working Python code
2
3def countTeams(rating):
4    count = 0
5    n = len(rating)
6    for j in range(n):
7        lower_left = sum(1 for i in range(j) if rating[i] < rating[j])
8        higher_left = sum(1 for i in range(j) if rating[i] > rating[j])
9        lower_right = sum(1 for k in range(j + 1, n) if rating[k] < rating[j])
10        higher_right = sum(1 for k in range(j + 1, n) if rating[k] > rating[j])
11        count += lower_left * higher_right + higher_left * lower_right
12    return count
13
14# Example usage
15print(countTeams([2,5,3,4,1]))  # Output: 3

Complexity note: The time complexity remains O(n²) due to the nested loops, but we avoid redundant checks by counting ratings, making it more efficient in practice. The space complexity is O(1) since we only use a few variables.

  • 1The order of ratings matters significantly in forming valid teams.
  • 2Counting lower and higher ratings efficiently reduces redundant checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.