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).

Input & Output

Example 1 — Basic Case
$ Input: rating = [2,5,3,4,1]
Output: 3
💡 Note: We can form teams: [2,3,4] (ascending), [5,4,1] (descending), [5,3,1] (descending). Total = 3 teams.
Example 2 — Minimum Size
$ Input: rating = [2,1,3]
Output: 0
💡 Note: No valid teams can be formed. [2,1,3] is neither ascending (2>1) nor descending (1<3).
Example 3 — All Ascending
$ Input: rating = [1,2,3,4,5]
Output: 10
💡 Note: All possible triplets form ascending teams: (1,2,3), (1,2,4), (1,2,5), (1,3,4), (1,3,5), (1,4,5), (2,3,4), (2,3,5), (2,4,5), (3,4,5).

Constraints

  • 3 ≤ rating.length ≤ 1000
  • 1 ≤ rating[i] ≤ 105
  • All the integers in rating are unique.

Visualization

Tap to expand
Count Number of Teams: [2,5,3,4,1]Soldier Ratings25341i=0i=1i=2i=3i=4Valid Teams Found:234Ascending: 2 < 3 < 4541Descending: 5 > 4 > 1531Descending: 5 > 3 > 1Total Teams: 3(1 ascending + 2 descending teams)
Understanding the Visualization
1
Input
Array of soldier ratings: [2,5,3,4,1]
2
Find Teams
Look for ascending (i<j<k) or descending (i>j>k) patterns
3
Output
Count of valid 3-soldier teams: 3
Key Takeaway
🎯 Key Insight: Fix the middle soldier and multiply the count of valid left partners with valid right partners
Asked in
Amazon 45 Microsoft 32 Google 28 Facebook 21
38.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen