Sponsored
Sponsored
This approach involves checking all possible combinations of three soldiers using nested loops to see if they can form a valid team. Although simple, this approach can be optimized by ensuring we scoot to the inner loops only when conditions are satisfied.
Time Complexity: O(n^3), where n is the length of the input array 'ratings'. This results from three nested loops each iterating over up to n elements.
Space Complexity: O(1), as it uses a constant amount of additional space.
1function numTeams(rating) {
2 let count = 0;
3 let n = rating.length;
4 for (let i = 0; i < n - 2; i++) {
5 for (let j = i + 1; j < n - 1; j++) {
6 for (let k = j + 1; k < n; k++) {
7 if ((rating[i] < rating[j] && rating[j] < rating[k]) ||
8 (rating[i] > rating[j] && rating[j] > rating[k])) {
9 count++;
10 }
11 }
12 }
13 }
14 return count;
15}
16
17const ratings = [2, 5, 3, 4, 1];
18console.log(numTeams(ratings)); // Output: 3
As with the other solutions, this JavaScript version checks all triplets using nested loops to find valid teams.
This approach reduces the number of nested loops from three to two by counting the number of elements to the left and right that satisfy the increasing or decreasing condition required for forming a team.
Time Complexity: O(n^2)
Space Complexity: O(1)
1function
The JavaScript solution also uses an efficient counting mechanism to reduce time complexity by assessing potential middle soldiers and checking suitable ordered pairs on each side.