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 Using Binary Indexed Tree (Fenwick Tree) INPUT n = 5 soldiers with ratings i=0 2 i=1 5 i=2 3 i=3 4 i=4 1 rating = [2, 5, 3, 4, 1] Valid Team Conditions: rating[i] < rating[j] < rating[k] OR rating[i] > rating[j] > rating[k] where i < j < k Find all valid teams of 3 ALGORITHM STEPS 1 Initialize BIT Create Fenwick Tree for counting elements 2 For each middle j Count smaller/larger on left using BIT query 3 Count right side Find smaller/larger on right of current j 4 Calculate teams Multiply: leftSmall*rightLarge + leftLarge*rightSmall BIT Query Example (j=2, rating=3) Left of j=2: [2, 5] smaller=1 (rating 2) larger=1 (rating 5) Right of j=2: [4, 1] smaller=1 (rating 1) larger=1 (rating 4) FINAL RESULT Valid Teams Found: Team 1 (Increasing) (0,2,3): 2 < 3 < 4 OK Team 2 (Increasing) (0,1,3): 2 < 5 -- invalid (2,3 not shown): 3 < 4 -- Team 2 (Decreasing) (1,2,4): 5 > 3 > 1 OK Team 3 (Decreasing) (1,3,4): 5 > 4 > 1 OK Output: 3 Key Insight: For each middle element j, use BIT to efficiently count elements smaller/larger on left side. Teams = (leftSmaller * rightLarger) + (leftLarger * rightSmaller). Time: O(n log n), Space: O(max rating) TutorialsPoint - Count Number of Teams | Binary Indexed Tree (Fenwick Tree) Time: O(n log n) | Space: O(n)
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