Count Number of Teams - Problem
In a military formation, there are n soldiers standing in a line, each with a unique rating value that represents their skill level. Your mission is to form special reconnaissance teams of exactly 3 soldiers each.
A valid team must follow strict formation rules:
- Choose 3 soldiers at positions
i < j < k - Their ratings must form either an ascending sequence (
rating[i] < rating[j] < rating[k]) or a descending sequence (rating[i] > rating[j] > rating[k])
For example, with ratings [2, 5, 3, 4, 1], you can form teams like:
- Ascending: positions (0,2,3) → ratings (2,3,4)
- Descending: positions (1,2,4) → ratings (5,3,1)
Goal: Count the total number of valid teams that can be formed. Note that soldiers can participate in multiple teams.
Input & Output
example_1.py — Basic Case
$
Input:
[2,5,3,4,1]
›
Output:
3
💡 Note:
Valid teams: (0,2,3) with ratings (2,3,4) ascending, (0,1,2) with ratings (2,5,3) descending, and (1,2,4) with ratings (5,3,1) descending
example_2.py — All Ascending
$
Input:
[1,2,3,4,5]
›
Output:
10
💡 Note:
All possible triplets form ascending teams: C(5,3) = 10 teams total. Examples: (1,2,3), (1,2,4), (1,2,5), (1,3,4), etc.
example_3.py — Minimum Length
$
Input:
[1,4,2]
›
Output:
1
💡 Note:
Only one valid team: positions (0,2,1) but indices must be in order, so (0,1,2) gives ratings (1,4,2) which forms a descending team after reordering
Constraints
- 3 ≤ n ≤ 1000
- 1 ≤ rating[i] ≤ 105
- All ratings are unique
- Need to count teams, not find them
Visualization
Tap to expand
Understanding the Visualization
1
Pick the Middle
Choose the middle person in each potential group
2
Count Left Partners
Count people to the left who are shorter/taller
3
Count Right Partners
Count people to the right who are taller/shorter
4
Multiply Combinations
Multiply left and right counts to get total valid groups
Key Takeaway
🎯 Key Insight: Fix the middle element and count valid partners on both sides - this transforms a complex combinatorial problem into simple counting and multiplication.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code