Problem
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).
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Here is the video explanation of below approaches:
Method 1 - Brute Force
We can use three nested loops to check all possible triplets. This approach is simple but not efficient for larger values of ( n ) (time complexity O(n^3)
).
Method 2 - Count Left and Right
- For each soldier at index ( j ), we can count the number of soldiers before ( j ) that are either less than or greater than the rating of ( j ).
- Similarly, count the number of soldiers after ( j ) that are either less than or greater than the rating of ( j ).
- Using these counts, we can determine the number of valid teams for which ( j ) is the middle soldier.
We will iterate through each soldier to collect these counts and then compute the number of valid teams.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
- 🧺 Space complexity:
O(1)
Method 3 - Recursion
- This problem is a variation of the Longest Increasing Subsequence LIS.
- Instead of finding the LIS and Longest Decreasing Subsequence (LDS), we need to count the total number of increasing and decreasing subsequences of length 3 in the given array.
- While LIS determines the maximum length of increasing subsequences, our goal here is to specifically focus on subsequences of length 3.
Code
|
|
Complexity
- ⏰ Time complexity:
O(2^n)
- Each element can be either included or excluded, leading to (O(2^n)) combinations in total.
- For each combination, checking if it forms a valid team takes constant time.
- 🧺 Space complexity:
O(n)
for recursion stack
Method 4 - Top Down DP with memoization
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
- The function is called with different values of
(ind, prev, count)
. ind
ranges from0
ton
.prev
can be any of then
indices or-1
, resulting inn + 1
possible values.count
ranges from0
to3
.
- The function is called with different values of
- 🧺 Space complexity:
O(n^2)
due to memoization table and recursion stack (of size ofO(n)
)
Method 5 - Bottom up DP
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
- 🧺 Space complexity:
O(n^2)