question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
โ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum-swaps-to-group-all-1s-together-ii | Python sliding window O(n) | python-sliding-window-on-by-abkc1221-d026 | \nclass Solution:\n def minSwaps(self, nums: List[int]) -> int:\n ones = nums.count(1)\n n = len(nums)\n res = ones\n start = 0\n | abkc1221 | NORMAL | 2022-02-23T11:01:03.005972+00:00 | 2022-02-23T11:01:03.006004+00:00 | 457 | false | ```\nclass Solution:\n def minSwaps(self, nums: List[int]) -> int:\n ones = nums.count(1)\n n = len(nums)\n res = ones\n start = 0\n end = ones-1\n zeroesInWindow = sum(num==0 for num in nums[start:end+1])\n \n while start < n:\n # print(start, end , zeroesInWindow)\n res = min(res, zeroesInWindow)\n if nums[start] == 0: zeroesInWindow -= 1 \n start += 1\n end += 1\n if nums[end%n] == 0: zeroesInWindow += 1\n \n return res\n``` | 2 | 0 | ['Sliding Window', 'Python', 'Python3'] | 1 |
minimum-swaps-to-group-all-1s-together-ii | C++ sliding window | c-sliding-window-by-colinyoyo26-iy4o | \nclass Solution {\npublic:\n int minSwaps(vector<int>& nums) {\n int n = nums.size(), res = INT_MAX;\n int ones = count(nums.begin(), nums.end | colinyoyo26 | NORMAL | 2022-01-24T12:24:13.496560+00:00 | 2022-01-24T12:24:13.496586+00:00 | 154 | false | ```\nclass Solution {\npublic:\n int minSwaps(vector<int>& nums) {\n int n = nums.size(), res = INT_MAX;\n int ones = count(nums.begin(), nums.end(), 1);\n int zcnt = 0;\n if (!ones)\n return 0;\n for (int l = 0, r = 0; l < n; r = (r + 1) % n) {\n zcnt += !nums[r];\n if (r - l + 1 == ones || r < l) {\n res = min(res, zcnt);\n zcnt -= !nums[l++];\n }\n }\n return res;\n }\n};\n``` | 2 | 0 | [] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Python3 Simple Solution | Sliding Window | python3-simple-solution-sliding-window-b-i3jg | Steps to follow -:\na) First of all count the number of ones in the array which will represent our window size.\nb) Make a variable to keep count of ones in cur | dynamite_ | NORMAL | 2022-01-14T08:03:14.371318+00:00 | 2022-01-14T08:03:55.043200+00:00 | 149 | false | Steps to follow -:\na) First of all count the number of ones in the array which will represent our window size.\nb) Make a variable to keep count of ones in current window and a variable to keep maximum ones count.\nc) Now, run a loop till twice of the size of array since we have given a circular array.\nd) Check if current element is 1 then increase our current window variable by 1.\ne) Also, keep a check if index is greater than window size and first element of window is 1 then decrease our current window variable by 1\nf) Modify maximum one count variable at the end of each loop with maximum of current window variable and maximum one count variable.\ng) Finally, return the difference of total ones and maximum one count variable.\n\n```\ndef minSwaps(self, nums: List[int]) -> int:\n\t\ttotalOnes = nums.count(1) #totalOnes is our window size\n n = len(nums)\n maxOnesInWindow = 0\n onesInCurrWindow = 0\n for i in range(n2):\n if nums[i%n]:\n onesInCurrWindow += 1\n if i >= totalOnes and nums[i%n-totalOnes]:\n onesInCurrWindow -= 1\n maxOnesInWindow = max(maxOnesInWindow,onesInCurrWindow)\n return totalOnes-maxOnesInWindow\n```\n\nPlease upvote if you find it helpful !!\n\t\t\n\t | 2 | 0 | ['Sliding Window', 'Python'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | java commented solution 100% faster o(n) time,o(1) space. easy to understanded commented code | java-commented-solution-100-faster-on-ti-w28j | pls do comment if any thing is not clear\n\n\nclass Solution {\n public int minSwaps(int[] nums) {\n | yash_52 | NORMAL | 2022-01-09T14:20:02.631001+00:00 | 2022-01-09T14:31:48.256667+00:00 | 207 | false | pls do comment if any thing is not clear\n\n```\nclass Solution {\n public int minSwaps(int[] nums) {\n //sliding window approach\n int n=nums.length;\n /*\n sliding window pattern\n step 1->we\'ll first calculate total no\'s of ones in our array \n **edge case:>(if(n==1||totalnoOfOne<=1) return 0) \n step 2->then we\'ll traverse in our array some what like sliding window\n step 3->and the size of the window will be the total no of ones in our array\n step 4->and from every window we will try to find no of ones present in that window\n step 5-> with hlp of no of ones we\'ll calculate no of zeros minzero=(totalOnes-onesinwindow) \n note:->thats what gonna be min no of swaps(minSwaps)\n step 6-> at the end minzero will be the no of swaps required\n \n */\n //calulate total no of one\'s\n int totalNoOfOnes=0;\n for(int i=0;i<n;i++){\n if(nums[i]==1)totalNoOfOnes++;\n }\n \n //edge case \n //mentioned below step 1\n if(n==1||totalNoOfOnes<=1)return 0;\n \n \n \n int preOne=0;\n for(int i=totalNoOfOnes-2;i>=0;i--){\n if(nums[i]==1)preOne++;\n }\n /*\n about pre one----------------------------------\n |\n V\n */\n \n /*\n cause the array is circular that\'s why we are calculating preOne what it is, will be clear with the given example \n example -> [0,1,0,0,0,1,1,0,0]\n so for this example we need to calculate total no one\'s present cause that what goona be the size of our window\n so, total no of one\'s=3\n index-> 0,1,2,3,4,5,6,7,8 \n [0,1,0,0,0,1,1,0,0]\n ^ \n |\n ******so for this index 8 this is what are window of size 3 will look like*****\n index-> 0,1,2,3,4,5,6,7,8 \n [0,1,0,0,0,1,1,0,0]\n ^ ^ ^ \n | | |\n\n *********in window this is what are preone will be***** \n index-> 0,1,2,3,4,5,6,7,8 \n [0,1,0,0,0,1,1,0,0]\n ^ ^ ^ \n | | |\n <--->\n preOne\n */\n \n \n // sliding window which will give minzeros out of all windows cause thats wahat gonna be min swaps (minSwaps) required:) \n \n int l=n-1,r=(n+totalNoOfOnes-2);\n int minSwaps=Integer.MAX_VALUE; //or minZeros\n while(l>=0){\n preOne+=nums[l];\n minSwaps=Math.min(minSwaps,totalNoOfOnes-preOne); //for this go to step5\n preOne-=nums[r%n];\n l--;\n r--;\n }\n return minSwaps;\n } \n} \n```\ndo consider upvote if its helpfull :)\n\t | 2 | 0 | ['Sliding Window', 'Java'] | 1 |
minimum-swaps-to-group-all-1s-together-ii | C++ | Sliding window | Intuition explained | c-sliding-window-intuition-explained-by-rcrlx | ```\n/\n1. For simplicity let us assume that the array is not circular.\n2. The outcome which we expect is a continuos window of ones\n3. We count the total num | shaashaa | NORMAL | 2022-01-09T12:46:49.862735+00:00 | 2022-01-09T13:02:40.962551+00:00 | 151 | false | ```\n/*\n1. For simplicity let us assume that the array is not circular.\n2. The outcome which we expect is a continuos window of ones\n3. We count the total number of ones in that input, this will be our window size, let us call it K\n4. We now iterate over all the windows of K size, in a sliding manner, calculating the diff = K-number of ones in current window\n5. Here diff gives us the no of swaps for that window. We maintain the value of min diff encountered and return that as an error.\n6. Now to deal with the circular array case, let\'s append the input array to itself\nFor ex: [1,1,0,0,1]\n\nmax no ones = K = 3\nmodfied i/p = [1,1,0,0,1,1,1,0,0,1]\nprocesing all windows ok size 3\ndiff = K-count of ones \n(1,1,0) 3-2 = 1\n(1,0,0) 3-1 = 2\n(0,0,1) 3-1 = 1\n(0,1,1) 3-2 = 1\n(1,1,1) 3-3 = 0\n(1,1,0) 3-2 = 1\n(1,0,0) 3-1 = 2\n(0,0,1) 3-1 = 2\n\nThe minimum value of diff = min swaps required = 0 \n\nNote : Instead of actually using extra space and appending input array to iteself, we can use the mod operator to access the values\n\n*/\n\nclass Solution {\npublic:\n int minSwaps(vector<int>& nums) {\n \n int onesCnt=0;\n \n int n = nums.size();\n for(int n : nums)\n if(n)\n onesCnt++;\n \n int start=0, end=0, ans=INT_MAX, currOnes=0;\n for(int end=0; end<2*n; end++)\n {\n currOnes+=nums[end%n];\n if(end-start >= onesCnt-1)\n {\n ans = min(ans, onesCnt-currOnes);\n currOnes-=nums[(start++)%n];\n } \n \n }\n \n return ans;\n \n }\n};\n | 2 | 0 | ['Sliding Window', 'C++'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Using sliding window technique, O(1) space, with comments, Simple & Easy, [C++] | using-sliding-window-technique-o1-space-wcft6 | Implementation\n\nUsing sliding window technique\nTime Complexity = O(N), Space Complexity = O(1)\n\nclass Solution {\npublic:\n int minSwaps(vector<int>& nu | akashsahuji | NORMAL | 2022-01-09T09:23:31.354704+00:00 | 2022-01-09T09:23:31.354736+00:00 | 125 | false | Implementation\n\n**Using sliding window technique\nTime Complexity = O(N), Space Complexity = O(1)**\n```\nclass Solution {\npublic:\n int minSwaps(vector<int>& nums) {\n int countOne = 0, n = nums.size();\n \n // count the total number of 1\'s present into array\n for(int itr = 0; itr < n; itr++){\n if(nums[itr]) countOne++;\n }\n \n // if no 1 is present then simply return 0\n if(countOne == 0) return 0;\n \n // taking the window size of the total 1\'s count\n int windowSize = countOne;\n int currCountOne = 0; \n \n // counting the number of 1\'s present into the starting window size from 0\n for(int itr = 0; itr < countOne; itr++){\n if(nums[itr]) currCountOne++;\n }\n \n // putting into the res, bcz res will hold the maximum number of 1\'s present into the current window size\n int res = currCountOne;\n for(int itr = 1; itr < n; itr++){\n \n // if leading element is 1 then decrement it by 1, bcz now it\'s not in a current window\n if(nums[itr-1]) currCountOne--;\n \n // if trailing element is 1 then increment it by 1, bcz now it\'s in a current window\n if(nums[(itr + windowSize - 1) % n]) currCountOne++;\n \n // storing the maximum count of 1\'s in a current window\n res = max(res, currCountOne);\n } \n \n // return total number of 1\'s in a array - maximum count of 1\'s in a current window\n return windowSize - res;\n }\n};\n```\nIf you find any issue in understanding the solution then comment below, will try to help you.\nIf you found my solution useful.\nSo **please do upvote and encourage me** to document all leetcode problems\uD83D\uDE03\nHappy Coding :) | 2 | 0 | ['C', 'Sliding Window'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | [c++] Sliding window O(N) Intuitive Approach | c-sliding-window-on-intuitive-approach-b-v6dl | Sliding Window Approach: \n\nWe will use sliding window Approach to track the how many max no of 1 are together, So for this we find the no of 1 in nums array a | manish1042447 | NORMAL | 2022-01-09T06:10:56.582805+00:00 | 2022-01-09T06:47:07.579098+00:00 | 107 | false | Sliding Window Approach: \n\nWe will use sliding window Approach to track the how many max no of 1 are together, So for this we find the no of 1 in nums array and we take window of that size we start sliding the window and we count how many no of 1 can be max present at a time in window If we got this then we just need to swap other 1 to neer-by position of large group of 1. \n\nTo track the window we use a queue and If new element which need to be pushed is 1 then you need to increment the currOne and we are tracking it\'s size if queue size is more than window size If yes then we pop one element and also if popped element is 1 then we need to decrement no of currOne. and we alway calculate the max of previous maxOne and currOne. After traversing though the array you need to return n - maxOne because that no of swap you need to to make all 1 together. We do traversing of first from (nums.size()-n) till end and then from 0 to end because it is a circular array. Please go through below code you will get the idea.\n\n```\nclass Solution {\npublic:\n int minSwaps(vector<int>& nums) {\n int n=0;\n for(auto it:nums){ // calculating the 1\n if(it)\n n++;\n }\n if(n==nums.size()){ // when all are one no need to do swapping\n return 0;\n }\n queue<int> slid;\n int maxONe=0; // no of 1 max 1 found in queue till that point of time\n int currOne=0;// no of 1 present in queue\n for(int i=nums.size()-n;i<nums.size();i++){//We start from nums.size()-n till end because this is round array\n if(slid.size()>=n){// we will pop only when queue have n element\n if(nums[i]){\n currOne++;// we increment 1 when we got new one\n } \n slid.push(nums[i]);\n if(slid.front()){\n currOne--; // we decrement when we got to know that top of queue which will initial element of \n\t\t\t\t\t\t\t\t\t//slide is 1 means currOne will need to be reduce\n }\n slid.pop();\n }\n else{\n if(nums[i]){\n currOne++;\n }\n slid.push(nums[i]);\n }\n maxONe=max(maxONe,currOne); \n }\n \n for(int i=0;i<nums.size();i++){ // after traversing from last we are good to start from 0th indxe we don\'t need \n\t\t\t\t\t\t\t\t//to check queue is empty because from above loop we should n element in queue\n if(nums[i]){\n currOne++;\n } \n slid.push(nums[i]);\n if(slid.front()){\n currOne--;\n }\n slid.pop();\n maxONe=max(maxONe,currOne); \n }\n return n-maxONe;\n }\n};\n```\n\nTOC=O(N) | 2 | 0 | ['C'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Easy & Short C++ | easy-short-c-by-masters_akt-wks2 | \nclass Solution {\npublic:\n int minSwaps(vector<int>& nums) {\n int ones = 0;\n for(int x: nums){\n if(x) ones++;\n }\n | Masters_Akt | NORMAL | 2022-01-09T04:28:36.357844+00:00 | 2022-01-09T04:28:36.357873+00:00 | 152 | false | ```\nclass Solution {\npublic:\n int minSwaps(vector<int>& nums) {\n int ones = 0;\n for(int x: nums){\n if(x) ones++;\n }\n int m = 0;\n for(int i=0;i<ones;i++){\n if(nums[i]) m++;\n }\n int mx = m;\n for(int i=1;i<nums.size();i++){\n if(nums[i-1]) m--;\n if(nums[(i-1+ones)%nums.size()]) m++;\n mx = max(mx, m);\n }\n return ones-mx;\n }\n};\n``` | 2 | 0 | ['C'] | 1 |
minimum-swaps-to-group-all-1s-together-ii | [C++] Clean Sliding Window Solution | c-clean-sliding-window-solution-by-realr-8j33 | Solution: We can account for the circular array constraint of the question by simply doubling the size of the array. The question then becomes, find the closest | realrr | NORMAL | 2022-01-09T04:02:25.044927+00:00 | 2022-01-09T04:04:30.046367+00:00 | 165 | false | **Solution:** We can account for the circular array constraint of the question by simply doubling the size of the array. The question then becomes, find the closest sliding window match with k (where k = the number of ones in nums) ones. The number of swaps needed is the number of mismatches (1 != 0) in the current window. The answer is the minimum number of swaps needed for any window. \n```\nint minSwaps(vector<int>& nums) {\n int N = nums.size(), ones = 0, mismatches = 0;\n for (int i = 0; i < N; i++) nums.push_back(nums[i]);\n for (int i = 0; i < N; i++) ones += nums[i] == 1;\n for (int i = 0; i < ones; i++) mismatches += nums[i] == 0;\n int ans = mismatches;\n for (int i = ones; i < 2 * N; i++) {\n if (nums[i] == 0) mismatches++;\n if (nums[i - ones] == 0) mismatches--;\n ans = min(ans, mismatches);\n }\n return ans;\n}\n``` | 2 | 1 | ['Sliding Window'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | C++ | Easy and best Soln | Faster | c-easy-and-best-soln-faster-by-itachi_sk-ksjd | \n\tclass Solution {\n\tpublic:\n int minSwaps(vector<int>& nums) {\n int sum = accumulate(nums.begin(), nums.end(), 0), m = 0, ma = 0;\n nums. | itachi_sks | NORMAL | 2022-01-09T04:01:17.322291+00:00 | 2022-01-09T04:01:17.322332+00:00 | 245 | false | ```\n\tclass Solution {\n\tpublic:\n int minSwaps(vector<int>& nums) {\n int sum = accumulate(nums.begin(), nums.end(), 0), m = 0, ma = 0;\n nums.insert(nums.end(), nums.begin(), nums.end());\n for(int i=0; i<sum; i++) {\n if(nums[i]==1) ma+=1;\n }\n int j = sum;\n m = max(m, ma);\n for(int i=1; i<=nums.size()-sum; i++) {\n if(nums[i-1]==1) ma--;\n if(nums[j]==1) ma++;\n j++;\n m = max(m, ma);\n }\n return sum-m;\n }\n};\n``` | 2 | 2 | [] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Minimum Swaps to Group 1s โ Sliding Window Approach || Beginner Friendly || Beats 79.09 || | minimum-swaps-to-group-1s-sliding-window-6jd0 | Hey everyone! ๐I recently solved the "Minimum Swaps to Group 1s" problem using a sliding window approach on a circular array. Since the array is circular, I dup | vigneshvicky2005 | NORMAL | 2025-04-10T10:00:22.479641+00:00 | 2025-04-10T10:00:22.479641+00:00 | 3 | false | Hey everyone! ๐
I recently solved the "Minimum Swaps to Group 1s" problem using a **sliding window approach** on a **circular array**. Since the array is circular, I duplicated it to handle wrap-around cases efficiently.
### ๐น **Intuition**
The goal is to minimize swaps needed to bring all `1`s together in a contiguous subarray. We can treat it like a **fixed-size sliding window**, where the window size is equal to the total number of `1`s in the array.
### ๐น **Approach**
1. **Count the total number of `1`s** in the array. This gives us our ideal window size.
2. **Duplicate the array** to simulate circular behavior.
3. **Use a sliding window** to track the number of `1`s in the window and compute the minimum swaps needed.
### ๐น **Complexity Analysis**
- **Time Complexity:** $$O(n)$$ โ Since we iterate over the array twice (once to count `1`s, once to slide the window).
- **Space Complexity:** $$O(n)$$ โ Due to array duplication.
### ๐น **Code (Java)**
```java
class Solution {
public int minSwaps(int[] nums) {
int n = nums.length;
int[] arr = new int[2*n];
int ones = 0;
for(int i = 0; i < n; i++ ) {
ones += nums[i];
}
for(int i = 0; i < 2*n; i++) {
arr[i] = nums[i % n];
}
int cur_one = 0;
for(int i = 0; i < ones; i++) {
cur_one += arr[i];
}
int min_swap = Integer.MAX_VALUE;
for(int i = ones; i < 2*n; i++) {
cur_one -= arr[i - ones];
cur_one += arr[i];
min_swap = Math.min(min_swap, ones - cur_one);
}
return min_swap;
}
}
```
### ๐ก **Final Thoughts**
I found that **sliding window** was the best approach to minimize swaps efficiently.
Would love to hear your feedback! Did anyone take a different approach? ๐
| 1 | 0 | ['Java'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Sliding Window O(n) switch JavaScript Solution | sliding-window-on-switch-javascript-solu-38x3 | IntuitionApproachComplexity
Time complexity:
O(n)
Space complexity:
O(1)Code | hadeeressam21 | NORMAL | 2025-03-25T20:24:54.059559+00:00 | 2025-03-25T20:24:54.059559+00:00 | 8 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1)
# Code
```javascript []
/**
* @param {number[]} nums
* @return {number}
*/
var minSwaps = function(nums) {
//count of 1's item
// will be the size of the sliding window
let cnt = nums.reduce((acc, curr) => acc+curr , 0)
let len = nums.length
//get the first sliding window (start point) with same legth of number of 1's appearance count
//get it 1's count existance
let slide = nums.slice(0, cnt).reduce((acc, curr) => acc+curr , 0)
//will be minues from **cnt** to get the number of 0's
let max = slide
for(let i=0 ; i<len ; i++){
//extend array by using MOD (%)
//extend sliding window by one
if(nums[(cnt+i)%len] === 1){
slide++
}
//remove one item from the begin of window as moving
if(nums[i] === 1){
slide--
}
//the max number of 1's exist =====> minimize the number of 0's exist of window
max = Math.max(max, slide)
}
return cnt - max
};
``` | 1 | 0 | ['Array', 'Sliding Window', 'JavaScript'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Simple Fixed Length Sliding Window Approach | simple-fixed-length-sliding-window-appro-2oaf | Approach
Count the total number of 1's in the array:
Iterate through the array and count how many 1s are present. Let's call this count k.
Sliding window app | Jonty_gupta_1204 | NORMAL | 2025-03-11T15:58:24.395451+00:00 | 2025-03-11T15:58:24.395451+00:00 | 25 | false | <!-- # Intuition -->
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
* Count the total number of 1's in the array:
* Iterate through the array and count how many 1s are present. Let's call this count k.
* Sliding window approach:
* Use a sliding window of size k to find the maximum number of 1s within any subarray of length k.
* Window shifting:
* Start with the window at the beginning of the array.
* Extend the window to the right, incrementing e. If the number is 1, increment a counter one.
* When the window exceeds size k, slide the window to the right by incrementing s (start of the window). If the number at s is 1, decrement one.
* Track the maximum number of 1's in the window:
* During each window slide, update the maxi to track the maximum number of 1s encountered in a window of size k.
* Calculate minimum swaps:
* The minimum swaps required to group all 1s together is the difference between k (total number of 1s) and maxi (maximum number of 1s in a sliding window of size k).
* Return the result:
* The result is k - maxi, which represents the minimum number of swaps needed.
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minSwaps(vector<int>& nums) {
int n = nums.size();
int k = 0;
for(int i = 0; i < n; i++){
if(nums[i] == 1) k++;
}
int s = 0, e = 0;
int one = 0, maxi = 0;
while(e < (n + k)){
if(e < k){
if(nums[e] == 1) one++;
}
else{
if(nums[e % n] == 1) one++;
if(nums[s] == 1) one--;
s++;
}
maxi = max(maxi, one);
e++;
}
return k - maxi;
}
};
``` | 1 | 0 | ['Array', 'Sliding Window', 'C++'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | C++ | 0ms - TC: 100% | Sliding Window | c-0ms-tc-100-sliding-window-by-ghozt777-asrr | Intuition
the key observation is that we can perform 2 tasks:
we can either group all the 1s together
or we can group all the 0s together (this means that all | ghozt777 | NORMAL | 2025-03-08T06:51:36.354603+00:00 | 2025-03-08T06:51:36.354603+00:00 | 35 | false | # Intuition
- the key observation is that we can perform 2 tasks:
- we can either group all the 1s together
- or we can group all the 0s together (this means that all the 1s are grouped together in the circular array)
# Approach
- we use sliding window to find the swaps required to get all the 1s together and all the 0s together
- step 1 : count the total number of 1s in the array this is our target aka `k`
- initialize the pointers to the window `start` and `end` = `0`
- now we start expanding the window using `end++`
- if the total count of the digits(`ones`+`zeroes`) becomes equal to the value `k` then we count all the `0`s in the window, this is the minimum number of swaps required for the current window. We keep track of the result in variable `res` and perform res = `min(res,zeroes)`
- next if we have ateast k digits we slide the window by performing `++start`
- We repeat this entire process but for `0s` instead of `1s` (because doing this will give us the minimum number of swaps for the 1s to be on the edges and since its a circular array they are grouped together -> Eg: `111100000111` all the 0s are grouped together and by default this pushes all the 1s to the edges and hence are grouped).
# Complexity
- Time complexity:
O(n) , n = length of the array
- Space complexity:
O(1) , constant space
# Code
```cpp []
class Solution {
public:
int minSwaps(vector<int>& nums) {
// k : indicates the total number of 1s we want together
int k = 0 ;
for(int x : nums) k += x == 1 ;
// we use sliding window ok size k to find the total number of 1s and 0s
// if there are x 0s in the window we need to swap them with 1s instead
// hence res = min(res,zeroes) ;
int start = 0 , end = 0 ;
int ones = 0, zeroes = 0 ;
int res = INT_MAX ;
while(end < nums.size()){
ones += nums[end] == 1 ;
zeroes += nums[end] == 0 ;
++end ;
// if we have found the limit, slide the window
if(ones + zeroes >= k){
res = min(res,zeroes) ;
ones -= nums[start] == 1 ;
zeroes -= nums[start] == 0 ;
++start ;
}
}
// perform the same operation but this time for 0s instead of 1s
k = 0 ;
for(int x : nums) k += x == 0 ;
start = 0 , end = 0 ;
ones = 0, zeroes = 0 ;
while(end < nums.size()){
ones += nums[end] == 1 ;
zeroes += nums[end] == 0 ;
++end ;
if(ones + zeroes >= k){
res = min(res,ones) ;
ones -= nums[start] == 1 ;
zeroes -= nums[start] == 0 ;
++start ;
}
}
return res ;
}
};
``` | 1 | 0 | ['Sliding Window', 'C++'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | C# | c-by-adchoudhary-ohsp | Code | adchoudhary | NORMAL | 2025-03-05T03:46:47.499429+00:00 | 2025-03-05T03:46:47.499429+00:00 | 4 | false | # Code
```csharp []
public class Solution {
public int MinSwaps(int[] nums)
{
int n = nums.Length;
// Step 1: Calculate total number of 1's
int totalOnes = 0;
foreach (int num in nums)
{
if (num == 1)
{
totalOnes++;
}
}
// Edge case: if there are no 1's or only one 1, no swaps needed
if (totalOnes <= 1)
{
return 0;
}
// Step 2: Compute the prefix sum array
int[] prefixSum = new int[n + 1];
for (int i = 0; i < n; i++)
{
prefixSum[i + 1] = prefixSum[i] + nums[i];
}
// Step 3: Find the minimum number of swaps required
int minSwaps = int.MaxValue;
// Check all possible windows of size totalOnes
for (int i = 0; i < n; i++)
{
int end = i + totalOnes - 1;
int currentOnes;
if (end < n)
{
currentOnes = prefixSum[end + 1] - prefixSum[i];
}
else
{
currentOnes = (prefixSum[n] - prefixSum[i]) + (prefixSum[end - n + 1]);
}
minSwaps = Math.Min(minSwaps, totalOnes - currentOnes);
}
return minSwaps;
}
}
``` | 1 | 0 | ['C#'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Sliding Window with detailed Explanation | Beats 90% | TC: O(n) | sliding-window-with-detailed-explanation-x0o6 | IntuitionWe need to group all 1s together in a circular binary array while making the fewest swaps.
Since the array is circular, the first and last elements ar | Ashwin__Anand__ | NORMAL | 2025-02-25T05:20:50.744396+00:00 | 2025-02-25T05:20:50.744396+00:00 | 9 | false | # Intuition
We need to group all `1`s together in a circular binary array while making the fewest swaps.
- Since the array is circular, the first and last elements are adjacent. Instead of treating it as a strict array, we can imagine extending it into a **linear form** by considering two copies of the array back-to-back.
- Our goal is to find a subarray (or window) of size equal to the total count of `1`s, which contains the **maximum number of `1`s** already grouped together.
- Once we find this window, the number of swaps required is simply the number of `0`s in this window, as those are the ones that need to be swapped.
# Approach
1. **Count the Total Number of `1`s (`totalOnes`)**
- Since all `1`s must be grouped together, the optimal window size should be `totalOnes`.
2. **Use a Sliding Window on a Virtual Extended Array**
- Since the array is circular, we extend it virtually using **modulo indexing**. This allows us to traverse the array efficiently without actually duplicating it.
- We maintain a **sliding window of size `totalOnes`**, keeping track of the number of `1`s in it.
3. **Find the Window with Maximum `1`s**
- We move the window across the array and update the count dynamically.
- The best window is the one that contains the maximum number of `1`s, as it requires the fewest swaps.
4. **Answer**
- The minimum swaps required is:
```
totalOnes - maxOnesInAWindow
```
- This gives the number of `0`s that need to be swapped with `1`s to form a contiguous group.
# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(1)$$
# Code
```java []
class Solution {
public int minSwaps(int[] nums) {
int totalOnes = 0;
int n = nums.length;
for(int i = 0; i < n; ++i) {
totalOnes += nums[i];
}
if(totalOnes == 0) return 0;
if(n < 2) return 0;
int currWindowOnes = 0;
int maxOnesTogether = 0;
int end = 0, start = 0;
while(start < n) {
currWindowOnes += nums[end % n];
if((end - start + 1) == totalOnes ||
(start > end && Math.abs(end - start) == totalOnes)) {
maxOnesTogether = Math.max(maxOnesTogether, currWindowOnes);
if(nums[start] == 1) {
currWindowOnes--;
}
start++;
}
end++;
}
return totalOnes - maxOnesTogether;
}
}
``` | 1 | 0 | ['Java'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Sliding Window Intution | | sliding-window-intution-by-sahil_lohar_n-o3ox | Intuitionafter reading problem we will get a ques in our mind that what is the exact position in whole nums, where we can put all ones together, is it in middle | sahil_lohar_nitr | NORMAL | 2025-02-08T09:39:13.273167+00:00 | 2025-02-08T09:39:13.273167+00:00 | 20 | false | # Intuition
after reading problem we will get a ques in our mind that what is the exact position in whole nums, where we can put all ones together, is it in middle or in leftmost or rightmost position ? but ques is asking to only make them together, so at the end, we will have all ones together so, can we check in whole array what is that position where all ones are together ? yes using sliding window of size = count of ones, we can check for a particular window that how much swaps this particular window require, and min swaps will be our ans and to eliminate circular propert of array we can append orignal array to itself
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minSwaps(vector<int>& nums) {
// after reading problem we will get a ques that what is the exact position in whole nums, where we can put all ones together, is it in middle or in leftmost or rightmost position ? but ques is asking to only make them together, so at the end, we will have all ones together so, can we check in whole array what is that position where all ones are together ? yes using sliding window of size = count of ones, we can check for a particular window that how much swaps this particular window require, and min swaps will be our ans and to eliminate circular propert of array we can append orignal array to itself
int n = nums.size(), i = 0, j = 0, cntOne = 0;
for (auto& it : nums)
if (it == 1)
cntOne++;
int k = cntOne, sum = 0, res = k;
nums.insert(nums.end(), nums.begin(), nums.end());
while (j < 2 * n) {
sum += nums[j];
if ((j - i + 1) > k) {
sum -= nums[i];
i++;
}
if ((j - i + 1) == k)
res = min(res, k - sum);
j++;
}
return res;
}
};
``` | 1 | 0 | ['C++'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | Most Intuitive Sliding Window solution | most-intuitive-sliding-window-solution-b-5ris | It was hard to come up with a solution for this, and honestly I failed a few times before I saw a hint and realized what needed to be done.The basic idea of the | greeky | NORMAL | 2025-01-20T20:01:23.142086+00:00 | 2025-01-20T20:01:23.142086+00:00 | 26 | false | It was hard to come up with a solution for this, and honestly I failed a few times before I saw a hint and realized what needed to be done.
The basic idea of the question is to count the number of 1s in the array (say `totalOnesCount`) and then to "Find the window if size `totalOnesCount` containing the maximum number of 1s (i.e. window with minimum 0s)". Once you understand this, the question is easy to solve.
Below are a few salient points for coming up with this solution:
1. Since the array is circular, we iterate from 0 to `len + totalOnesCount -1` to find that window.
2. The sliding window is of a fixed length `totalOnesCount`.
3. Once we maximize 1s in a given window, we automatically minimize the number of 0s in that window and hence we minimize the number of swaps.
4. Use modulo operator to not exceed the array boundaries.
Here is a summary of the solution below:
1. Count the total number of 1s in the array. Let's call it `totalOnesCount`.
2. Create `currOnesCount` to keep track of 1s in the current window of length `totalOnesCount` and initialize to 0.
3. Create `res` to keep track of the minimum number of swaps.
4. Iterate from index 0 to `len + totalOnesCount - 1` since the 1s could be wrapped around.
5. Add the current number to `currOnesCount`.
6. If the size of the window is less than `totalOnesCount`, continue.
7. If the size of the window is equal to `totalOnesCount`, update `res`, while removing the first number from the window. Note that the new size of the window is `totalOnesCount - 1` currently, but it'll be `totalOnesCount` in the next iteration.
8. Return `res`.
# Code
```java []
class Solution {
public int minSwaps(int[] nums) {
int len = nums.length, totalOnesCount = 0;
// Count the number of 1's
for (int num : nums) {
totalOnesCount += num;
}
int currOnesCount = 0, res = Integer.MAX_VALUE;
// len+totalOnesCount for circular array
for (int i = 0; i < len + totalOnesCount; i++) {
// Add the current element
currOnesCount += nums[i % len];
// If the window size is less than totalOnesCount, continue
if (i < totalOnesCount - 1) {
continue;
}
// Update res
res = Math.min(res, totalOnesCount - currOnesCount);
// Remove the first element from the window
currOnesCount -= nums[(i - totalOnesCount + 1) % len];
}
return res;
}
}
``` | 1 | 0 | ['Java'] | 0 |
minimum-swaps-to-group-all-1s-together-ii | [Java] Clean code with comments and very Easy to understand | java-clean-code-with-comments-and-very-e-ake3 | IntuitionThe basic idea is to:1 - Calculate the number of 1s in the array. This will be the size of our sliding window.
2 - Slide a window of this size through | Arjun15597 | NORMAL | 2025-01-08T03:36:40.105817+00:00 | 2025-01-08T03:36:40.105817+00:00 | 18 | false | # Intuition
The basic idea is to:
1 - Calculate the number of 1s in the array. This will be the size of our sliding window.
2 - Slide a window of this size through the array with Circluar Approach, counting the number of 0s inside the window.
3 - The minimum number of 0s encountered in any window will give us the minimum swaps required.
# Approach
1 - Count the number of 1s.
2 - Count zeros in the initial window
3 - Slide the window with circular Approach
4 - Track the minimum zeros
5 - Return the result
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(1)
# Code
```java []
class Solution {
public int minSwaps(int[] data) {
int windowSize = 0;
int minSwaps = Integer.MAX_VALUE;
int zerosInWindow = 0;
int n = data.length;
// Step 1: Calculate the number of 1's in the array, which will be the window size
for(int i = 0; i < n; i++){
if(data[i] == 1){
windowSize++;
}
}
// Step 2: Count the number of zeros in the initial window (first `windowSize` elements)
for(int i = 0; i < windowSize; i++){
if(data[i] == 0){
zerosInWindow++;
}
}
minSwaps = Math.min(minSwaps, zerosInWindow);
// Step 3: Slide the window through the array in circular Way
for(int i = windowSize; i < n + windowSize - 1; i++){
// Add the new element coming into the window with circular logic
if(data[i % n] == 0){
zerosInWindow++;
}
// Remove the element that is sliding out of the window
if(data[i - windowSize] == 0){
zerosInWindow--; // If it's zero, decrement the zeros count
}
// Update the minimum number of zeros found in the window
minSwaps = Math.min(minSwaps, zerosInWindow);
}
return minSwaps;
}
}
``` | 1 | 0 | ['Java'] | 0 |
count-number-of-teams | C++/Java O(n * n) and O(n log n) | cjava-on-n-and-on-log-n-by-votrubac-rumg | For each soldier, count how many soldiers on the left and right have less and greater ratings.\n\nThis soldier can form less[left] * greater[right] + greater[le | votrubac | NORMAL | 2020-03-29T04:01:16.611146+00:00 | 2020-04-03T08:12:33.595099+00:00 | 50,112 | false | For each soldier, count how many soldiers on the left and right have `less` and `greater` ratings.\n\nThis soldier can form `less[left] * greater[right] + greater[left] * less[right]` teams.\n\n**Complexity Considerations**\n\nThe straightforward approach to count soldiers yields a quadratic solution. You might be tempted to use a set or something to count soldiers in O(log n) time.\n\nYou can find a rating in a set in O(log n), however, counting smaller (or larger) elements will still be linear. Unless you implement BST where each node tracks count of left children, a set approach will be quadratic as well.\n\n> Update: see approach 2 below for a simple linearithmic solution below.\n \n #### Approach 1: Count Left and Right\n**C++**\n```cpp\nint numTeams(vector<int>& rating) {\n int res = 0;\n for (auto i = 1; i < rating.size() - 1; ++i) {\n int less[2] = {}, greater[2] = {};\n for (auto j = 0; j < rating.size(); ++j) {\n if (rating[i] < rating[j])\n ++less[j > i];\n if (rating[i] > rating[j])\n ++greater[j > i];\n }\n res += less[0] * greater[1] + greater[0] * less[1];\n }\n return res;\n}\n```\n**Java**\n```java\npublic int numTeams(int[] rating) {\n int res = 0;\n for (int i = 1; i < rating.length - 1; ++i) {\n int less[] = new int[2], greater[] = new int[2];\n for (int j = 0; j < rating.length; ++j) {\n if (rating[i] < rating[j])\n ++less[j > i ? 1 : 0];\n if (rating[i] > rating[j])\n ++greater[j > i ? 1 : 0];\n }\n res += less[0] * greater[1] + greater[0] * less[1];\n }\n return res;\n}\n```\n**Complexity Analysis**\n- Time: O(n * n) \n- Memory: O(1)\n\n#### Approach 2: Sort Left and Right\nWe can store ratings on the left and right in the sorted order. As we process soldiers left-to-right, we move their rating from the right bucket to the left bucket.\n\nWe can use BST to store sorted ratings, and insert/remove ratings in O(log n). However, standard containers like `set` or `map` won\'t tell us how many elements are smaller than the given rating. You can locate a rating in O(log n), but counting elements smaller or larger will still br linear.\n\nTherefore, we need to implement our own BST that can tell us how many elements are less than a given rating in O(log n). For that, we will track the number of left children for each node, and accumulate it as we search in the tree. See `count` function below for more details.\n\n**Additional Considerations**\nWe need to balance BST in order to achieve O(n log n) time complexity in the worst case. Also, the simple implementation below does not handle duplicates.\n\n**C++**\n```cpp\nstruct Tree {\n Tree *left = nullptr, *right = nullptr;\n int val = 0, cnt_left = 0;\n Tree(int val) : val(val) {}\n};\nint numTeams(vector<int>& rating) {\n Tree left(rating.front()), right(rating.back());\n int res = 0, sz = rating.size();\n for (auto i = 1; i < sz - 1; ++i)\n insert(&right, rating[i]);\n for (auto i = 1; i < sz - 1; ++i) {\n remove(&right, rating[i]);\n int l_sm = count(&left, rating[i]), l_lg = i - l_sm;\n int r_sm = count(&right, rating[i]), r_lg = (sz - 1 - i - r_sm) ;\n res += l_sm * r_lg + l_lg * r_sm;\n insert(&left, rating[i]);\n }\n return res;\n}\nint count(Tree* root, int val) {\n if (root == nullptr)\n return 0;\n if (val < root->val)\n return count(root->left, val);\n return 1 + root->cnt_left + count(root->right, val);\n}\nTree* insert(Tree* root, int val) {\n if (root == nullptr)\n return new Tree(val);\n if (val < root->val) {\n ++root->cnt_left;\n root->left = insert(root->left, val);\n }\n else\n root->right = insert(root->right, val);\n return root;\n}\nTree* remove(Tree* root, int val) {\n if (root == nullptr)\n return nullptr;\n if (root->val == val) {\n if (root->left == nullptr)\n return root->right;\n auto rightmost = root->left;\n while (rightmost->right != nullptr)\n rightmost = rightmost->right;\n rightmost->right = root->right;\n return root->left;\n }\n if (val < root->val) {\n --root->cnt_left;\n root->left = remove(root->left, val);\n }\n else\n root->right = remove(root->right, val);\n return root;\n}\n```\n**Complexity Analysis**\n- Time: O(n log n) in the average case. We need to implement tree balancing to achieve O(n log n) in the worst case. \n- Memory: O(n) for the trees. | 389 | 12 | [] | 46 |
count-number-of-teams | python, >97.98%, simple logic and very detailed explanation | python-9798-simple-logic-and-very-detail-df8m | \nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n asc = dsc = 0\n for i,v in enumerate(rating):\n llc = rgc = lgc | rmoskalenko | NORMAL | 2020-04-05T19:02:30.144894+00:00 | 2020-04-05T19:11:42.113255+00:00 | 15,729 | false | ```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n asc = dsc = 0\n for i,v in enumerate(rating):\n llc = rgc = lgc = rlc =0\n for l in rating[:i]:\n if l < v:\n llc += 1\n if l > v:\n lgc += 1\n for r in rating[i+1:]:\n if r > v:\n rgc += 1\n if r < v:\n rlc += 1\n asc += llc * rgc\n dsc += lgc * rlc \n return asc + dsc\n```\n\nThe logic is so simple - it actually passed all tests on the first try :)\n\nSo here is how it works.\n\nWe are going to have a main for loop and we are going to pick one element from the `ratings` list at a time. Then we are going to have two other loops. One is going to scan all elements before and the other one is going to scan all elements after. Those two loops will count number of elements less and greater than the one we picked. So let\'s say we have 2 elements less than the selected one to the left and 3 elements greater to the right. That means the number of ascending sequences we can build is `2 * 3 = 6` . Now we just need to extend the same logic to all descending sequences and return the total.\n\nIt may sound crazy, but if you want a more visual picture - imaging walking accross city and crossing streets. You come to a street, look at your left, count, cross half way, look to the right , count, then finish crossing the street and walk to the next one. While the underlying activity is quite different, when you write the code - that visual helps to implement the proper structure.\n\nOk, so let\'s write the code now:\n\nFirst, let\'s define the variables. Technically we can use just one counter, but for clarity, let\'s use two, `asc` for ascending and `dsc` for descendig sequences:\n\n```\n asc = dsc = 0\n```\n\nNow let\'s start our main loop to scan all elements:\n\n```\n for i,v in enumerate(rating):\n```\n\nInside every cycle we are going to use 4 local counters: `llc` - stands for `Left, Less, Counter` - count of elements less then the current one to the left. `rgc` - `Right, Greater, Counter` - count of elements greater than the current one to the right. I think you can guess what the other 2 are?\n\n```\n llc = rgc = lgc = rlc =0\n```\n\nOk, now we picked some element, we are going to look to the left and count element less and greater than the current one:\n\n```\n for l in rating[:i]:\n if l < v:\n llc += 1\n if l > v:\n lgc += 1\n```\n\nAnd now we look to the right:\n\n```\n for r in rating[i+1:]:\n if r > v:\n rgc += 1\n if r < v:\n rlc += 1\n```\n\nAnd update the total counters:\n\n```\n asc += llc * rgc\n dsc += lgc * rlc \n```\n\nOnce the main loop is complete, we just return the total total:\n```\n return asc + dsc\n```\n\nOk, all done!\n\nWe can add some polishing touches:\n\n1. Since we really need just one counter, we can replace `asc` and `dsc` with a single counter `c`.\n2. Since we need to have same elements to the left and to the right, we can skip the the first and the last elements in the main loop scan.\n3. Replace 2nd `if` with `elsif` - that would reduce number of logical operations - since if the first condition is `True`, the second won\'t be evaluated.\n\nSo here is the improved version:\n\n\n```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n c = 0\n for i,v in enumerate(rating[1:-1]):\n llc = rgc = lgc = rlc = 0\n for l in rating[:i+1]:\n if l < v:\n llc += 1\n elif l > v:\n lgc += 1\n for r in rating[i+2:]:\n if r > v:\n rgc += 1\n elif r < v:\n rlc += 1\n c += llc * rgc + lgc * rlc \n return c\n```\n\nI can a few tests and it looks like the 1st version peaked at 94% and the 2nd at 97.98%, so maybe those improvements added a few per cents.\n\nThanks for reading! | 270 | 6 | [] | 45 |
count-number-of-teams | C++ solutions O(n ^ 3), O(n ^ 2) and O(nlogn) | c-solutions-on-3-on-2-and-onlogn-by-cpcs-bhsb | Trivial O(n ^ 3)\n\n\nclass Solution {\n \n \npublic:\n int numTeams(vector<int>& rating) {\n int r = 0;\n const int n = rating.size();\n | cpcs | NORMAL | 2020-03-29T07:20:38.156575+00:00 | 2020-03-29T07:20:38.156611+00:00 | 13,670 | false | Trivial O(n ^ 3)\n```\n\nclass Solution {\n \n \npublic:\n int numTeams(vector<int>& rating) {\n int r = 0;\n const int n = rating.size();\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < i; ++j) {\n for (int k = 0; k < j; ++k) {\n if ((rating[i] < rating[j] && rating[j] < rating[k]) || (rating[i] > rating[j] && rating[j] > rating[k])) {\n ++r;\n }\n }\n }\n }\n return r;\n \n }\n};\n```\n\nTrivial O(n ^ 2)\n\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n const int n = rating.size();\n int r = 0;\n for (int i = 0; i < n; ++i) {\n int x1 = 0, x2 = 0, y1 = 0, y2 = 0;\n for (int j = 0; j < n; ++j) {\n if (j < i) {\n if (rating[j] < rating[i]) {\n ++x1;\n } else {\n ++x2;\n }\n } else if (j > i) {\n if (rating[j] < rating[i]) {\n ++y1;\n } else {\n ++y2;\n }\n }\n }\n r += x1 * y2 + x2 * y1;\n }\n return r;\n \n }\n};\n```\n\nWith the help of map and tree index array we can achieve O(nlogn):\n\n```\nclass Solution {\n void update(vector<int> &v, int i, const int d) {\n for (; i < v.size(); v[i] += d, i += (i & -i));\n }\n \n int presum(const vector<int> &v, int i) {\n int r = 0;\n for (; i; r += v[i], i -= (i & -i));\n return r;\n }\n \npublic:\n int numTeams(vector<int>& rating) {\n map<int, int> have;\n for (int x : rating) {\n have[x];\n }\n int n = 0;\n vector<int> after(rating.size() + 1);\n for (auto& t : have) { \n update(after, t.second = ++n, 1);\n }\n vector<int> before(n + 1);\n int r = 0;\n for (int i = 0; i < n; ++i) {\n const int x = have[rating[i]], t1 = presum(before, x), t2 = presum(after, x);\n r += t1 * (n - i - t2) + (i - t1) * (t2 - 1);\n update(after, x, -1);\n update(before, x, 1);\n }\n return r;\n \n }\n};\n``` | 105 | 2 | [] | 14 |
count-number-of-teams | [Python] Easy O(N^2) DP solution | python-easy-on2-dp-solution-by-alviniac-djj0 | \nfrom collections import defaultdict\n\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n if len(rating) < 3:\n return 0\n | alviniac | NORMAL | 2020-03-29T04:18:23.742078+00:00 | 2020-03-29T04:23:32.825541+00:00 | 11,264 | false | ```\nfrom collections import defaultdict\n\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n if len(rating) < 3:\n return 0\n \n greater = defaultdict(int)\n less = defaultdict(int)\n res = 0\n \n\t\t# greater[i] is the number of elements after index i greater than ratings[i]\n for i in range(len(rating)-1):\n for j in range(i+1, len(rating)):\n if rating[j] > rating[i]:\n greater[i] += 1\n else:\n less[i] += 1\n \n\t\t# Accumulate counts\n for i in range(len(rating)-2):\n for j in range(i+1, len(rating)):\n if rating[i] < rating[j]:\n res += greater[j]\n else:\n res += less[j]\n \n return res\n``` | 86 | 2 | [] | 22 |
count-number-of-teams | Easiest Code Ever - Python - Top 97% Speed - O( n log n ) Combinatorial | easiest-code-ever-python-top-97-speed-o-wz8lv | Easiest Code Ever - Python - Top 97% Speed - O( n log n ) Combinatorial\n\nThe code below simply loops through the array taking an element "x" as the pivot. Usi | aragorn_ | NORMAL | 2020-07-07T20:33:03.360191+00:00 | 2021-05-25T09:42:17.669522+00:00 | 8,711 | false | **Easiest Code Ever - Python - Top 97% Speed - O( n log n ) Combinatorial**\n\nThe code below simply loops through the array taking an element "x" as the pivot. Using this pivot, we count separately the number of values:\n1. **Lower** than "x" to the **left** (lo_L)\n2. **Higher** than "x" to the **left** (hi_L)\n1. **Lower** than "x" to the **right** (lo_R)\n2. **Higher** than "x" to the **right** (hi_R)\n\nThese values are then combined to update our result variable:\n* result += lo_L * hi_R + hi_L * lo_R\n\nThe idea makes a lot of sense after a moment (a detailed explanation of the formula can be found below).\n\nNow, the 4 tracked variables can be obtained in two ways:\n1. The best way is to use SortedLists containing all the values to the Left and Right of our pivot. Using binary search, we can find the index of our pivot in these lists, and quickly deduce the number of elements higher or lower. This allows us to have a O( n log n ) solution.\n2. Otherwise, we can use two nested loops to build our counting variables primitively. This gives us a O(n^2) solution.\n\nBoth code versions are presented below. I hope the explanation was helpful. Cheers,\n\n```\n# Version A: [Top Speed] O(n log n) solution using SortedLists to calculate our 4 counting variables in Log(n) time.\nfrom sortedcontainers import SortedList\nclass Solution:\n def count_low_high(self,sl,x):\n lo = sl.bisect_left(x)\n hi = len(sl) - lo\n return lo, hi\n \n def numTeams(self, A):\n result = 0\n left = SortedList()\n right = SortedList(A)\n for x in A:\n right.remove(x)\n lo_L, hi_L = self.count_low_high(left ,x)\n lo_R, hi_R = self.count_low_high(right,x)\n result += lo_L*hi_R + hi_L*lo_R\n left .add(x)\n return result\n```\n\n```\n# Version B: O(n^2) solution with (primitive) nested loops for building our 4 counting variables.\nclass Solution:\n def numTeams(self, A):\n L = len(A)\n result = 0\n for j in range(1,L-1):\n x, lo_L, lo_R, hi_L, hi_R = A[j], 0, 0, 0, 0\n for i in range(j):\n if A[i]<x:\n lo_L += 1\n else:\n hi_L += 1\n for k in range(j+1,L):\n if A[k]<x:\n lo_R += 1\n else:\n hi_R += 1\n result += lo_L*hi_R + hi_L*lo_R\n return result\n```\n\n\n**PS.** Detailed explanation of the formula ``` lower_left * higher_right + higher_left * lower_right``` :\n\nThe formula comes from the fact that we need to create triplets with the form ```a<b<c``` or```a>b>c```. Since ```b``` can be regarded as the pivotal point dividing the sequence, we notice that we can form triplets by choosing:\n1) For ```a<b<c```, choose any number ```a``` (to the left) lower than ```b```, and any number ```c``` to the right which is higher. The total number of combinations for this case is ```lower_left*higher_right```.\n2) For ```a>b>c```, reverse the previous process. Choose any number ```a``` to the left higher than ```b```, and any subsequent number ```c``` which is lower. This creates a total number of combinations ```higher_left*lower_right```.\n\nAs you can see, summing the combinations for both alternatives gives us the formula ```total = lower_left*higher_right + higher_left*lower_right```. The rest of the code is just book-keeping, and choosing good Data Structures to handle the problem easily. | 85 | 2 | ['Python', 'Python3'] | 11 |
count-number-of-teams | [Java] Detailed Explanation - TreeSet -> BIT (Fenwick Tree) - O(NlogN) | java-detailed-explanation-treeset-bit-fe-g058 | Updated: Thanks @nmxm for pointing out: TreeSet has the limitation when calling size() on its portion Set (See comment below). There are still some tree structu | frankkkkk | NORMAL | 2020-03-29T04:15:50.733390+00:00 | 2020-03-29T05:47:13.669046+00:00 | 7,949 | false | **Updated:** Thanks @nmxm for pointing out: TreeSet has the limitation when calling size() on its portion Set (See comment below). There are still some tree structures to use so that we can make it logN, for example -> [Binary Indexed Tree (Fenwick Tree)](https://en.wikipedia.org/wiki/Fenwick_tree). I keep the original code by using TreeSet, and also updated a new version of code by using BIT.\n\n**Ideal:** For every middle solider, count how many soliders smaller than it on the left (cL), how many soliders larger than it on the right (cR). For this solider as middle one, cL * cR is the result of ascending order. Also, do same thing for the descending order.\n\n**Code:** Iterate all soliders as it is the middle solider. And then, count number of solider smaller than it, and bigger than it from both left and right halves by **Fenwick Tree or TreeSet (*deprecated*).**\n\n#### 1. BIT (Fenwick Tree)\n```java\npublic int numTeams(int[] rating) {\n \n\tif (rating.length < 3) return 0;\n\n\tint N = rating.length;\n\n\tint[] leftTree = new int[(int) 1e5 + 1];\n\tint[] rightTree = new int[(int) 1e5 + 1];\n\n\tfor (int r : rating) update(rightTree, r, 1);\n\n\tint res = 0;\n\tfor (int r : rating) {\n\t\tupdate(rightTree, r, -1);\n\t\tres += (getPrefixSum(leftTree, r - 1) * getSuffixSum(rightTree, r + 1)); // count increase\n\t\tres += (getSuffixSum(leftTree, r + 1) * getPrefixSum(rightTree, r - 1)); // count decrease\n\t\tupdate(leftTree, r, 1);\n\t}\n\n\treturn res;\n}\n\nprivate void update(int[] BIT, int index, int val) {\n\twhile (index < BIT.length) {\n\t\tBIT[index] += val;\n\t\tindex += index & (-index);\n\t}\n}\n\nprivate int getPrefixSum(int[] BIT, int index) {\n\tint sum = 0;\n\twhile (index > 0) {\n\t\tsum += BIT[index];\n\t\tindex -= index & (-index);\n\t}\n\treturn sum;\n}\n\nprivate int getSuffixSum(int[] BIT, int index) {\n\treturn getPrefixSum(BIT, (int) 1e5) - getPrefixSum(BIT, index - 1);\n}\n```\n#### 2. TreeSet (Deprecated)\n```java\n// TreeSet Solution (Deprecated): Using .size() on One of the Views of the Set is still O(n)\nif (rating.length < 3) return 0;\n \nint N = rating.length;\n\nTreeSet<Integer> leftSet = new TreeSet<>();\nTreeSet<Integer> rightSet = new TreeSet<>();\n\nfor (int i = N - 1; i >= 0; --i) rightSet.add(rating[i]);\n\nint res = 0;\nfor (int i = 0; i < N; ++i) {\n\tint r = rating[i];\n\t\n\trightSet.remove(r);\n\tres += (leftSet.headSet(r).size() * rightSet.tailSet(r).size()); \t// count increase\n\tres += (leftSet.tailSet(r).size() * rightSet.headSet(r).size()); \t// count decrease\n\tleftSet.add(r);\n}\n\nreturn res;\n``` | 72 | 2 | [] | 16 |
count-number-of-teams | Beats 100 % O(n log n) | Binary Index Tree | Java | Python | C++ | JavaScript/TypeScript | Go | Rust | beats-100-on-log-n-binary-index-tree-jav-tfhj | Problem Overview:\n\nThe problem presents a scenario involving a line of soldiers, each with a unique rating. The task is to form teams under specific condition | kartikdevsharma_ | NORMAL | 2024-07-27T07:10:40.249477+00:00 | 2024-07-27T17:55:49.558120+00:00 | 13,506 | false | # Problem Overview:\n\nThe problem presents a scenario involving a line of soldiers, each with a unique rating. The task is to form teams under specific conditions:\n\n1. **Team Composition:**\n - Each team must consist of exactly 3 soldiers.\n\n2. **Selection Criteria:**\n - The soldiers in a team must be chosen from left to right in the line.\n - This means if we select soldiers at positions i, j, and k, then i < j < k must be true.\n\n3. **Rating Requirements:**\n - The ratings of the selected soldiers must follow one of two patterns:\n a) Strictly increasing: rating[i] < rating[j] < rating[k]\n b) Strictly decreasing: rating[i] > rating[j] > rating[k]\n\n4. **Multiple Team Participation:**\n - A soldier can be part of multiple teams.\n\n5. **Goal:**\n - Count the total number of valid teams that can be formed following these rules.\n\n**Key Considerations:**\n- The order of soldiers in the line is crucial and cannot be changed.\n- The uniqueness of ratings ensures no two soldiers have the same rating.\n- We need to consider both ascending and descending rating patterns.\n- The same trio of soldiers should not be counted twice (once for ascending and once for descending).\n\n**Constraints:**\n- The number of soldiers (n) is between 3 and 1000.\n- Each rating is a positive integer not exceeding 10^5.\n- All ratings are unique.\n\nThe challenge lies in efficiently counting all valid teams without explicitly forming each team, especially for larger inputs where a brute-force approach would be time-consuming.\n\n---\n# Binary Index Tree\n### Intuition\n\nThe problem asks us to count the number of valid teams of three soldiers that can be formed from a line of soldiers, where each soldier has a unique rating. A valid team must satisfy either an ascending or descending order of ratings, and the soldiers must be in the correct order in the line.\n\nThe key insight is that for each soldier, we need to count how many valid pairs of soldiers we can form with this soldier as the middle element. This means we need to find:\n1. For ascending order: How many soldiers to the left have a lower rating, and how many to the right have a higher rating.\n2. For descending order: How many soldiers to the left have a higher rating, and how many to the right have a lower rating.\n\nThe product of these two counts will give us the number of valid teams for each soldier as the middle element. Summing this for all soldiers will give us the total number of valid teams.\n\n### Approach\n\n\n1. **Preprocessing**:\n - Create a list of Soldier objects, each containing the rating and original index.\n - Sort this list based on the ratings.\n - Create an index map that maps each soldier\'s original index to their position in the sorted list.\n\n2. **Counting Teams**:\n - Use a Binary Indexed Tree (BIT) or Fenwick Tree to efficiently count the number of soldiers with ratings less than or greater than a given rating.\n - Iterate through the soldiers in their original order.\n - For each soldier, count the number of valid teams they can form as the middle element, both for ascending and descending order.\n\n3. **Binary Indexed Tree (BIT)**:\n - Use a BIT to perform efficient range sum queries and updates.\n - This allows us to count the number of soldiers with ratings less than or greater than a given rating in logarithmic time.\n\n**Pseudo-code** for the approach:\n\n```\nfunction numTeams(rating):\n n = length of rating\n if n < 3:\n return 0\n\n // Create and sort list of soldiers\n soldiers = empty list\n for i from 0 to n-1:\n add Soldier(rating[i], i) to soldiers\n sort soldiers by rating\n\n // Create index map\n indexMap = array of size n\n for i from 0 to n-1:\n indexMap[soldiers[i].index] = i\n\n teams = 0\n \n // Count ascending teams\n teams += countTeams(indexMap, n, ascending=true)\n \n // Count descending teams\n teams += countTeams(indexMap, n, ascending=false)\n \n return teams\n\nfunction countTeams(indexMap, n, ascending):\n bit = array of size n+1 initialized with zeros\n teams = 0\n\n for i from 0 to n-1:\n rank = indexMap[i] + 1\n \n if ascending:\n left = getSum(bit, rank - 1)\n right = n - rank - (getSum(bit, n) - getSum(bit, rank))\n else:\n left = getSum(bit, n) - getSum(bit, rank)\n right = rank - 1 - getSum(bit, rank - 1)\n \n teams += left * right\n update(bit, rank, 1)\n \n return teams\n\nfunction update(bit, index, val):\n while index < length of bit:\n bit[index] += val\n index += index & (-index)\n\nfunction getSum(bit, index):\n sum = 0\n while index > 0:\n sum += bit[index]\n index -= index & (-index)\n return sum\n\nclass Soldier:\n rating: integer\n index: integer\n\n constructor(rating, index):\n this.rating = rating\n this.index = index\n\n compareTo(other):\n return this.rating - other.rating\n```\n\nLet\'s go through the main steps in more detail:\n\n1. **Preprocessing**:\n - We create a list of Soldier objects, each containing the rating and the original index of a soldier.\n - We sort this list based on the ratings. This gives us the relative order of soldiers by their ratings.\n - We create an index map that, for each soldier\'s original index, stores their position in the sorted list. This allows us to quickly find out how many soldiers have a lower or higher rating than a given soldier.\n\n2. **Counting Teams**:\n - We use a function `countTeams` to count the number of valid teams for both ascending and descending order.\n - For each soldier (in their original order):\n - We find their rank (position in the sorted list) using the index map.\n - We count how many soldiers to their left have a lower rating (for ascending) or higher rating (for descending).\n - We count how many soldiers to their right have a higher rating (for ascending) or lower rating (for descending).\n - The product of these two counts gives us the number of valid teams with this soldier as the middle element.\n - We add this to our total count of teams.\n\n3. **Binary Indexed Tree (BIT)**:\n - We use a BIT to efficiently perform range sum queries and updates.\n - The BIT is used to keep track of how many soldiers we\'ve seen so far with each rating.\n - The `update` function adds a soldier to the BIT.\n - The `getSum` function counts how many soldiers we\'ve seen so far with a rating less than or equal to a given rating.\n\nThe key to the efficiency of this algorithm is the use of the Binary Indexed Tree. It allows us to perform both updates and queries in O(log n) time, which is crucial for the overall time complexity of the algorithm.\n\n### Dry Run\n\nLet\'s use the example: rating = [2, 5, 3, 4, 1]\n\n1. **Create and sort Soldier objects:**\n\n | Original Index | 0 | 1 | 2 | 3 | 4 |\n |----------------|---|---|---|---|---|\n | Rating | 2 | 5 | 3 | 4 | 1 |\n | Sorted Order | 1 | 5 | 2 | 3 | 4 |\n | Sorted Index | 0 | 4 | 1 | 2 | 3 |\n\n2. **Create indexMap:**\n\n | Original Index | 0 | 1 | 2 | 3 | 4 |\n |----------------|---|---|---|---|---|\n | indexMap value | 1 | 4 | 2 | 3 | 0 |\n\n3. **Count ascending teams:**\n We process soldiers in their original order, using the BIT to count smaller elements to the left.\n\n | Step | Index | Rating | Smaller Left | Larger Right | Teams | BIT Update |\n |------|-------|--------|--------------|--------------|-------|------------|\n | 1 | 0 | 2 | 0 | 3 | 0 | [0,1,0,0,0,0] |\n | 2 | 1 | 5 | 1 | 0 | 0 | [0,1,0,0,0,1] |\n | 3 | 2 | 3 | 1 | 1 | 1 | [0,1,0,1,0,1] |\n | 4 | 3 | 4 | 2 | 0 | 0 | [0,1,0,1,1,1] |\n | 5 | 4 | 1 | 0 | 4 | 0 | [1,1,0,1,1,1] |\n\n Total ascending teams: 1\n\n4. **Count descending teams:**\n We process soldiers in reverse order, using the BIT to count larger elements to the left.\n\n | Step | Index | Rating | Larger Left | Smaller Right | Teams | BIT Update |\n |------|-------|--------|-------------|---------------|-------|------------|\n | 1 | 4 | 1 | 0 | 0 | 0 | [0,1,0,0,0,0] |\n | 2 | 3 | 4 | 1 | 1 | 1 | [0,1,0,0,1,0] |\n | 3 | 2 | 3 | 1 | 1 | 1 | [0,1,0,1,1,0] |\n | 4 | 1 | 5 | 3 | 0 | 0 | [0,1,0,1,1,1] |\n | 5 | 0 | 2 | 1 | 1 | 1 | [0,1,1,1,1,1] |\n\n Total descending teams: 3\n\n5. **Final result:**\n Total teams = Ascending teams + Descending teams = 1 + 3 = 4\n\nThis is how we process each soldier, using the BIT to efficiently count the number of valid teams they can form as the middle member. The BIT allows us to quickly query the count of elements to the left that satisfy our condition (smaller for ascending, larger for descending) and update these counts.\n\nThe final answer of 4 represents all valid teams: (2,3,4), (5,3,1), (5,4,1), and (5,3,2).\n\n### Complexity\n\n- **Time complexity: O(n log n)**\n - Sorting the soldiers takes O(n log n) time.\n - We iterate through all soldiers once, and for each soldier, we perform constant number of BIT operations, each taking O(log n) time.\n - Therefore, the overall time complexity is O(n log n).\n\n- **Space complexity: O(n)**\n - We use additional space for the list of soldiers, the index map, and the BIT, each of size O(n).\n - Therefore, the overall space complexity is O(n).\n\n---\n\n### Code\n```Java []\nimport java.util.*;\n\nclass Solution {\n public int numTeams(int[] rating) {\n int n = rating.length;\n if (n < 3) return 0;\n \n // Create a list of soldiers with their ratings and indices\n List<Soldier> soldiers = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n soldiers.add(new Soldier(rating[i], i));\n }\n \n // Sort soldiers by rating\n Collections.sort(soldiers);\n \n int[] indexMap = new int[n];\n for (int i = 0; i < n; i++) {\n indexMap[soldiers.get(i).index] = i;\n }\n \n int teams = 0;\n \n // Count ascending teams\n teams += countTeams(indexMap, n, true);\n \n // Count descending teams\n teams += countTeams(indexMap, n, false);\n \n return teams;\n }\n \n private int countTeams(int[] indexMap, int n, boolean ascending) {\n int[] bit = new int[n + 1];\n int teams = 0;\n \n for (int i = 0; i < n; i++) {\n int rank = indexMap[i] + 1;\n int left = ascending ? getSum(bit, rank - 1) : getSum(bit, n) - getSum(bit, rank);\n int right = ascending ? n - rank - (getSum(bit, n) - getSum(bit, rank)) : rank - 1 - getSum(bit, rank - 1);\n teams += left * right;\n update(bit, rank, 1);\n }\n \n return teams;\n }\n \n private void update(int[] bit, int index, int val) {\n while (index < bit.length) {\n bit[index] += val;\n index += index & (-index);\n }\n }\n \n private int getSum(int[] bit, int index) {\n int sum = 0;\n while (index > 0) {\n sum += bit[index];\n index -= index & (-index);\n }\n return sum;\n }\n \n private class Soldier implements Comparable<Soldier> {\n int rating;\n int index;\n \n Soldier(int rating, int index) {\n this.rating = rating;\n this.index = index;\n }\n \n @Override\n public int compareTo(Soldier other) {\n return Integer.compare(this.rating, other.rating);\n }\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n if (n < 3) return 0;\n \n vector<pair<int, int>> soldiers;\n for (int i = 0; i < n; i++) {\n soldiers.push_back({rating[i], i});\n }\n sort(soldiers.begin(), soldiers.end());\n \n vector<int> indexMap(n);\n for (int i = 0; i < n; i++) {\n indexMap[soldiers[i].second] = i;\n }\n \n return countTeams(indexMap, n, true) + countTeams(indexMap, n, false);\n }\n \nprivate:\n int countTeams(const vector<int>& indexMap, int n, bool ascending) {\n vector<int> bit(n + 1, 0);\n int teams = 0;\n \n for (int i = 0; i < n; i++) {\n int rank = indexMap[i] + 1;\n int left = ascending ? getSum(bit, rank - 1) : getSum(bit, n) - getSum(bit, rank);\n int right = ascending ? n - rank - (getSum(bit, n) - getSum(bit, rank)) : rank - 1 - getSum(bit, rank - 1);\n teams += left * right;\n update(bit, rank, 1);\n }\n \n return teams;\n }\n \n void update(vector<int>& bit, int index, int val) {\n while (index < bit.size()) {\n bit[index] += val;\n index += index & (-index);\n }\n }\n \n int getSum(const vector<int>& bit, int index) {\n int sum = 0;\n while (index > 0) {\n sum += bit[index];\n index -= index & (-index);\n }\n return sum;\n }\n};\n```\n```Python []\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n if n < 3:\n return 0\n \n soldiers = sorted([(r, i) for i, r in enumerate(rating)])\n index_map = [0] * n\n for i, (_, idx) in enumerate(soldiers):\n index_map[idx] = i\n \n def count_teams(ascending: bool) -> int:\n bit = [0] * (n + 1)\n teams = 0\n \n for i in range(n):\n rank = index_map[i] + 1\n left = self.get_sum(bit, rank - 1) if ascending else self.get_sum(bit, n) - self.get_sum(bit, rank)\n right = n - rank - (self.get_sum(bit, n) - self.get_sum(bit, rank)) if ascending else rank - 1 - self.get_sum(bit, rank - 1)\n teams += left * right\n self.update(bit, rank, 1)\n \n return teams\n \n return count_teams(True) + count_teams(False)\n \n def update(self, bit: List[int], index: int, val: int) -> None:\n while index < len(bit):\n bit[index] += val\n index += index & (-index)\n \n def get_sum(self, bit: List[int], index: int) -> int:\n total = 0\n while index > 0:\n total += bit[index]\n index -= index & (-index)\n return total\n```\n```Go []\nfunc numTeams(rating []int) int {\n n := len(rating)\n if n < 3 {\n return 0\n }\n \n type soldier struct {\n rating, index int\n }\n \n soldiers := make([]soldier, n)\n for i, r := range rating {\n soldiers[i] = soldier{r, i}\n }\n sort.Slice(soldiers, func(i, j int) bool {\n return soldiers[i].rating < soldiers[j].rating\n })\n \n indexMap := make([]int, n)\n for i, s := range soldiers {\n indexMap[s.index] = i\n }\n \n countTeams := func(ascending bool) int {\n bit := make([]int, n+1)\n teams := 0\n \n for i := 0; i < n; i++ {\n rank := indexMap[i] + 1\n var left, right int\n if ascending {\n left = getSum(bit, rank-1)\n right = n - rank - (getSum(bit, n) - getSum(bit, rank))\n } else {\n left = getSum(bit, n) - getSum(bit, rank)\n right = rank - 1 - getSum(bit, rank-1)\n }\n teams += left * right\n update(bit, rank, 1)\n }\n \n return teams\n }\n \n return countTeams(true) + countTeams(false)\n}\n\nfunc update(bit []int, index, val int) {\n for index < len(bit) {\n bit[index] += val\n index += index & (-index)\n }\n}\n\nfunc getSum(bit []int, index int) int {\n sum := 0\n for index > 0 {\n sum += bit[index]\n index -= index & (-index)\n }\n return sum\n}\n```\n```Rust []\nimpl Solution {\n pub fn num_teams(rating: Vec<i32>) -> i32 {\n let n = rating.len();\n if n < 3 {\n return 0;\n }\n \n let mut soldiers: Vec<(i32, usize)> = rating.iter().enumerate().map(|(i, &r)| (r, i)).collect();\n soldiers.sort_unstable_by_key(|&(r, _)| r);\n \n let mut index_map = vec![0; n];\n for (i, &(_, idx)) in soldiers.iter().enumerate() {\n index_map[idx] = i;\n }\n \n let count_teams = |ascending: bool| -> i32 {\n let mut bit = vec![0; n + 1];\n let mut teams = 0;\n \n for i in 0..n {\n let rank = index_map[i] + 1;\n let left = if ascending {\n Self::get_sum(&bit, rank - 1)\n } else {\n Self::get_sum(&bit, n) - Self::get_sum(&bit, rank)\n };\n let right = if ascending {\n n - rank - (Self::get_sum(&bit, n) - Self::get_sum(&bit, rank))\n } else {\n rank - 1 - Self::get_sum(&bit, rank - 1)\n };\n teams += left * right;\n Self::update(&mut bit, rank, 1);\n }\n \n teams as i32\n };\n \n count_teams(true) + count_teams(false)\n }\n \n fn update(bit: &mut Vec<usize>, mut index: usize, val: usize) {\n while index < bit.len() {\n bit[index] += val;\n index += index & (!index + 1);\n }\n }\n \n fn get_sum(bit: &Vec<usize>, mut index: usize) -> usize {\n let mut sum = 0;\n while index > 0 {\n sum += bit[index];\n index -= index & (!index + 1);\n }\n sum\n }\n}\n```\n```JavaScript []\n/**\n * @param {number[]} rating\n * @return {number}\n */\nvar numTeams = function(rating) {\n const n = rating.length;\n if (n < 3) return 0;\n \n const soldiers = rating.map((r, i) => [r, i]).sort((a, b) => a[0] - b[0]);\n const indexMap = new Array(n).fill(0);\n for (let i = 0; i < n; i++) {\n indexMap[soldiers[i][1]] = i;\n }\n \n const countTeams = (ascending) => {\n const bit = new Array(n + 1).fill(0);\n let teams = 0;\n \n for (let i = 0; i < n; i++) {\n const rank = indexMap[i] + 1;\n const left = ascending ? getSum(bit, rank - 1) : getSum(bit, n) - getSum(bit, rank);\n const right = ascending ? n - rank - (getSum(bit, n) - getSum(bit, rank)) : rank - 1 - getSum(bit, rank - 1);\n teams += left * right;\n update(bit, rank, 1);\n }\n \n return teams;\n };\n \n const update = (bit, index, val) => {\n while (index < bit.length) {\n bit[index] += val;\n index += index & (-index);\n }\n };\n \n const getSum = (bit, index) => {\n let sum = 0;\n while (index > 0) {\n sum += bit[index];\n index -= index & (-index);\n }\n return sum;\n };\n \n return countTeams(true) + countTeams(false);\n};\n```\n```TypeScript []\nfunction numTeams(rating: number[]): number {\n const n: number = rating.length;\n if (n < 3) return 0;\n \n const soldiers: [number, number][] = rating.map((r, i): [number, number] => [r, i]).sort((a, b) => a[0] - b[0]);\n const indexMap: number[] = new Array(n).fill(0);\n for (let i = 0; i < n; i++) {\n indexMap[soldiers[i][1]] = i;\n }\n \n const countTeams = (ascending: boolean): number => {\n const bit: number[] = new Array(n + 1).fill(0);\n let teams: number = 0;\n \n for (let i = 0; i < n; i++) {\n const rank: number = indexMap[i] + 1;\n const left: number = ascending ? getSum(bit, rank - 1) : getSum(bit, n) - getSum(bit, rank);\n const right: number = ascending ? n - rank - (getSum(bit, n) - getSum(bit, rank)) : rank - 1 - getSum(bit, rank - 1);\n teams += left * right;\n update(bit, rank, 1);\n }\n \n return teams;\n };\n \n const update = (bit: number[], index: number, val: number): void => {\n while (index < bit.length) {\n bit[index] += val;\n index += index & (-index);\n }\n };\n \n const getSum = (bit: number[], index: number): number => {\n let sum: number = 0;\n while (index > 0) {\n sum += bit[index];\n index -= index & (-index);\n }\n return sum;\n };\n \n return countTeams(true) + countTeams(false);\n}\n\n```\n---\n\n# Approach 2\n\n### Intuition\n\nThis approach for the problem is based on the observation that for each soldier, we can count the number of valid teams they can be a part of by considering them as the middle element of a team. \n\nThe key insights are:\n1. For each soldier, we need to count how many soldiers to their left have lower and higher ratings.\n2. Similarly, we need to count how many soldiers to their right have lower and higher ratings.\n3. The number of ascending teams with this soldier as the middle element is the product of lower ratings to the left and higher ratings to the right.\n4. The number of descending teams with this soldier as the middle element is the product of higher ratings to the left and lower ratings to the right.\n5. By summing these counts for all soldiers, we get the total number of valid teams.\n\nThis approach doesn\'t use traditional dynamic programming with memoization, but it does use the principle of breaking down the problem into smaller subproblems and combining their results.\n\n### Approach\n\n1. **Iterate through all soldiers:**\n - For each soldier, consider them as the potential middle element of a team.\n\n2. **Count smaller and larger elements:**\n - For each soldier, count the number of soldiers with smaller and larger ratings to their left and right.\n\n3. **Calculate teams:**\n - For ascending teams: multiply the count of smaller ratings to the left with larger ratings to the right.\n - For descending teams: multiply the count of larger ratings to the left with smaller ratings to the right.\n\n4. **Sum up all teams:**\n - Add the number of ascending and descending teams for each soldier to get the total count.\n\n# Pseudo-code\n\n```\nfunction numTeams(rating):\n totalTeams = 0\n soldierCount = length of rating\n\n for currentSoldier from 0 to soldierCount - 1:\n totalTeams += countTeams(rating, currentSoldier, soldierCount)\n\n return totalTeams\n\nfunction countTeams(rating, currentSoldier, soldierCount):\n leftCounts = countSmallerAndLarger(rating, 0, currentSoldier, rating[currentSoldier])\n rightCounts = countSmallerAndLarger(rating, currentSoldier + 1, soldierCount, rating[currentSoldier])\n\n ascendingTeams = leftCounts[0] * rightCounts[1]\n descendingTeams = leftCounts[1] * rightCounts[0]\n\n return ascendingTeams + descendingTeams\n\nfunction countSmallerAndLarger(rating, start, end, reference):\n smaller = 0\n larger = 0\n\n for i from start to end - 1:\n if rating[i] < reference:\n smaller++\n else if rating[i] > reference:\n larger++\n\n return [smaller, larger]\n```\n\n### Dry Run\n\nLet\'s use the example: rating = [2, 5, 3, 4, 1]\n\nWe\'ll go through the process for each soldier:\n\n1. **Soldier with rating 2 (index 0):**\n - Left counts: [] -> [0, 0]\n - Right counts: [5, 3, 4, 1] -> [1, 3]\n - Ascending teams: 0 * 3 = 0\n - Descending teams: 0 * 1 = 0\n - Total teams: 0\n\n2. **Soldier with rating 5 (index 1):**\n - Left counts: [2] -> [1, 0]\n - Right counts: [3, 4, 1] -> [3, 0]\n - Ascending teams: 1 * 0 = 0\n - Descending teams: 0 * 3 = 0\n - Total teams: 0\n\n3. **Soldier with rating 3 (index 2):**\n - Left counts: [2, 5] -> [1, 1]\n - Right counts: [4, 1] -> [1, 1]\n - Ascending teams: 1 * 1 = 1\n - Descending teams: 1 * 1 = 1\n - Total teams: 2\n\n4. **Soldier with rating 4 (index 3):**\n - Left counts: [2, 5, 3] -> [2, 1]\n - Right counts: [1] -> [1, 0]\n - Ascending teams: 2 * 0 = 0\n - Descending teams: 1 * 1 = 1\n - Total teams: 1\n\n5. **Soldier with rating 1 (index 4):**\n - Left counts: [2, 5, 3, 4] -> [0, 4]\n - Right counts: [] -> [0, 0]\n - Ascending teams: 0 * 0 = 0\n - Descending teams: 4 * 0 = 0\n - Total teams: 0\n\nTotal teams = 0 + 0 + 2 + 1 + 0 = 3\n\nThe final answer of 3 represents all valid teams: (2,3,4), (5,3,1), and (5,4,1).\n\n### Complexity\n\n- **Time complexity: O(n^2)**\n - We iterate through all n soldiers.\n - For each soldier, we count smaller and larger elements to their left and right, which takes O(n) time.\n - Therefore, the overall time complexity is O(n^2).\n\n- **Space complexity: O(1)**\n - We only use a constant amount of extra space for variables and small arrays.\n - The space complexity is independent of the input size.\n\nThis approach trades time complexity for space complexity compared to the Binary Indexed Tree approach. It\'s simpler to implement and uses less space, but it\'s less efficient for larger inputs due to its quadratic time complexity.\n\n---\n### Code\n\n```Java []\nclass Solution {\n public int numTeams(int[] rating) {\n int totalTeams = 0;\n int soldierCount = rating.length;\n\n for (int currentSoldier = 0; currentSoldier < soldierCount; currentSoldier++) {\n totalTeams += countTeams(rating, currentSoldier, soldierCount);\n }\n\n return totalTeams;\n }\n\n private int countTeams(int[] rating, int currentSoldier, int soldierCount) {\n int[] leftCounts = countSmallerAndLarger(rating, 0, currentSoldier, rating[currentSoldier]);\n int[] rightCounts = countSmallerAndLarger(rating, currentSoldier + 1, soldierCount, rating[currentSoldier]);\n\n int ascendingTeams = leftCounts[0] * rightCounts[1];\n int descendingTeams = leftCounts[1] * rightCounts[0];\n\n return ascendingTeams + descendingTeams;\n }\n\n private int[] countSmallerAndLarger(int[] rating, int start, int end, int reference) {\n int smaller = 0, larger = 0;\n\n for (int i = start; i < end; i++) {\n if (rating[i] < reference) {\n smaller++;\n } else if (rating[i] > reference) {\n larger++;\n }\n }\n\n return new int[]{smaller, larger};\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int totalTeams = 0;\n int soldierCount = rating.size();\n\n for (int currentSoldier = 0; currentSoldier < soldierCount; currentSoldier++) {\n totalTeams += countTeams(rating, currentSoldier, soldierCount);\n }\n\n return totalTeams;\n }\n\nprivate:\n int countTeams(const vector<int>& rating, int currentSoldier, int soldierCount) {\n auto leftCounts = countSmallerAndLarger(rating, 0, currentSoldier, rating[currentSoldier]);\n auto rightCounts = countSmallerAndLarger(rating, currentSoldier + 1, soldierCount, rating[currentSoldier]);\n\n int ascendingTeams = leftCounts.first * rightCounts.second;\n int descendingTeams = leftCounts.second * rightCounts.first;\n\n return ascendingTeams + descendingTeams;\n }\n\n pair<int, int> countSmallerAndLarger(const vector<int>& rating, int start, int end, int reference) {\n int smaller = 0, larger = 0;\n\n for (int i = start; i < end; i++) {\n if (rating[i] < reference) {\n smaller++;\n } else if (rating[i] > reference) {\n larger++;\n }\n }\n\n return {smaller, larger};\n }\n};\n```\n```Python []\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n total_teams = 0\n soldier_count = len(rating)\n\n for current_soldier in range(soldier_count):\n total_teams += self.count_teams(rating, current_soldier, soldier_count)\n\n return total_teams\n\n def count_teams(self, rating: List[int], current_soldier: int, soldier_count: int) -> int:\n left_counts = self.count_smaller_and_larger(rating, 0, current_soldier, rating[current_soldier])\n right_counts = self.count_smaller_and_larger(rating, current_soldier + 1, soldier_count, rating[current_soldier])\n\n ascending_teams = left_counts[0] * right_counts[1]\n descending_teams = left_counts[1] * right_counts[0]\n\n return ascending_teams + descending_teams\n\n def count_smaller_and_larger(self, rating: List[int], start: int, end: int, reference: int) -> Tuple[int, int]:\n smaller, larger = 0, 0\n\n for i in range(start, end):\n if rating[i] < reference:\n smaller += 1\n elif rating[i] > reference:\n larger += 1\n\n return smaller, larger\n```\n```Go []\nfunc numTeams(rating []int) int {\n totalTeams := 0\n soldierCount := len(rating)\n\n for currentSoldier := 0; currentSoldier < soldierCount; currentSoldier++ {\n totalTeams += countTeams(rating, currentSoldier, soldierCount)\n }\n\n return totalTeams\n}\n\nfunc countTeams(rating []int, currentSoldier, soldierCount int) int {\n leftCounts := countSmallerAndLarger(rating, 0, currentSoldier, rating[currentSoldier])\n rightCounts := countSmallerAndLarger(rating, currentSoldier+1, soldierCount, rating[currentSoldier])\n\n ascendingTeams := leftCounts[0] * rightCounts[1]\n descendingTeams := leftCounts[1] * rightCounts[0]\n\n return ascendingTeams + descendingTeams\n}\n\nfunc countSmallerAndLarger(rating []int, start, end, reference int) [2]int {\n smaller, larger := 0, 0\n\n for i := start; i < end; i++ {\n if rating[i] < reference {\n smaller++\n } else if rating[i] > reference {\n larger++\n }\n }\n\n return [2]int{smaller, larger}\n}\n```\n```Rust []\nimpl Solution {\n pub fn num_teams(rating: Vec<i32>) -> i32 {\n let mut total_teams = 0;\n let soldier_count = rating.len();\n\n for current_soldier in 0..soldier_count {\n total_teams += Self::count_teams(&rating, current_soldier, soldier_count);\n }\n\n total_teams\n }\n\n fn count_teams(rating: &[i32], current_soldier: usize, soldier_count: usize) -> i32 {\n let left_counts = Self::count_smaller_and_larger(rating, 0, current_soldier, rating[current_soldier]);\n let right_counts = Self::count_smaller_and_larger(rating, current_soldier + 1, soldier_count, rating[current_soldier]);\n\n let ascending_teams = left_counts.0 * right_counts.1;\n let descending_teams = left_counts.1 * right_counts.0;\n\n ascending_teams + descending_teams\n }\n\n fn count_smaller_and_larger(rating: &[i32], start: usize, end: usize, reference: i32) -> (i32, i32) {\n let mut smaller = 0;\n let mut larger = 0;\n\n for i in start..end {\n if rating[i] < reference {\n smaller += 1;\n } else if rating[i] > reference {\n larger += 1;\n }\n }\n\n (smaller, larger)\n }\n}\n```\n```JavaScript []\n/**\n * @param {number[]} rating\n * @return {number}\n */\nvar numTeams = function(rating) {\n let totalTeams = 0;\n const soldierCount = rating.length;\n\n for (let currentSoldier = 0; currentSoldier < soldierCount; currentSoldier++) {\n totalTeams += countTeams(rating, currentSoldier, soldierCount);\n }\n\n return totalTeams;\n};\n\nfunction countTeams(rating, currentSoldier, soldierCount) {\n const leftCounts = countSmallerAndLarger(rating, 0, currentSoldier, rating[currentSoldier]);\n const rightCounts = countSmallerAndLarger(rating, currentSoldier + 1, soldierCount, rating[currentSoldier]);\n\n const ascendingTeams = leftCounts[0] * rightCounts[1];\n const descendingTeams = leftCounts[1] * rightCounts[0];\n\n return ascendingTeams + descendingTeams;\n}\n\nfunction countSmallerAndLarger(rating, start, end, reference) {\n let smaller = 0, larger = 0;\n\n for (let i = start; i < end; i++) {\n if (rating[i] < reference) {\n smaller++;\n } else if (rating[i] > reference) {\n larger++;\n }\n }\n\n return [smaller, larger];\n}\n```\n```TypeScript []\nfunction numTeams(rating: number[]): number {\n let totalTeams = 0;\n const soldierCount = rating.length;\n\n for (let currentSoldier = 0; currentSoldier < soldierCount; currentSoldier++) {\n totalTeams += countTeams(rating, currentSoldier, soldierCount);\n }\n\n return totalTeams;\n}\n\nfunction countTeams(rating: number[], currentSoldier: number, soldierCount: number): number {\n const leftCounts = countSmallerAndLarger(rating, 0, currentSoldier, rating[currentSoldier]);\n const rightCounts = countSmallerAndLarger(rating, currentSoldier + 1, soldierCount, rating[currentSoldier]);\n\n const ascendingTeams = leftCounts[0] * rightCounts[1];\n const descendingTeams = leftCounts[1] * rightCounts[0];\n\n return ascendingTeams + descendingTeams;\n}\n\nfunction countSmallerAndLarger(rating: number[], start: number, end: number, reference: number): [number, number] {\n let smaller = 0, larger = 0;\n\n for (let i = start; i < end; i++) {\n if (rating[i] < reference) {\n smaller++;\n } else if (rating[i] > reference) {\n larger++;\n }\n }\n\n return [smaller, larger];\n}\n``` | 66 | 3 | ['Array', 'Dynamic Programming', 'Binary Indexed Tree', 'C++', 'Java', 'Go', 'TypeScript', 'Python3', 'Rust', 'JavaScript'] | 12 |
count-number-of-teams | Beats 99.83% users... Result attached in the soln.... | beats-9983-users-result-attached-in-the-m8ufd | My Result:\n\n\n\n# Code\nPython []\nclass Solution:\n\n # alt, for perf test\n\n def numTeams(self, rating: List[int]) -> int:\n\n l = []\n\n | Aim_High_212 | NORMAL | 2024-07-29T00:10:19.670806+00:00 | 2024-07-29T00:38:43.402471+00:00 | 31,543 | false | # My Result:\n\n\n\n# Code\n``` Python []\nclass Solution:\n\n # alt, for perf test\n\n def numTeams(self, rating: List[int]) -> int:\n\n l = []\n\n sr = sorted(rating)\n\n low = {}\n\n for idx,r in enumerate(sr):\n\n low[r] = idx\n\n res = 0\n\n n = len(rating)\n\n for idx,r in enumerate(rating):\n\n i = bisect.bisect(l, r)\n\n l.insert(i,r)\n\n j = low[r] - i\n\n res+=i*(n-1-idx-j)+j*(idx-i)\n\n return res\n\n def numTeams2(self, rating: List[int]) -> int:\n\n ans,n = 0,len(rating)\n\n for j in range(n):\n\n # for any middle position j find counts less than rating[j] in [0..j) and (j..n) ranges\n\n llt,lgt = 0,0\n\n for i in range(j):\n\n llt += rating[i] < rating[j]\n\n lgt += rating[i] > rating[j]\n\n rlt,rgt = 0,0\n\n for k in range(j+1,n):\n\n rlt += rating[k] < rating[j]\n\n rgt += rating[k] > rating[j]\n\n ans += llt*rgt + lgt*rlt \n\n return ans\n\n # bf,tle\n\n def numTeams1(self, rating: List[int]) -> int:\n\n ans,n = 0,len(rating)\n\n for i in range(n):\n\n for j in range(i+1,n):\n\n for k in range(j+1,n):\n\n ans += 1 if rating[i] < rating[j] < rating[k] or rating[i] > rating[j] > rating[k] else 0\n\n return ans \n```\n``` Java []\nclass Solution {\n public int numTeams(int[] rating) {\n int n = rating.length;\n if (n < 3) return 0;\n\n int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;\n for (int num : rating) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n \n int[] leftTree = new int[max - min + 2];\n int[] rightTree = new int[max - min + 2];\n \n for (int num : rating) {\n update(rightTree, num - min, 1);\n }\n \n int count = 0;\n for (int i = 0; i < n; i++) {\n update(rightTree, rating[i] - min, -1);\n \n int lessLeft = query(leftTree, rating[i] - min - 1);\n int greaterLeft = i - lessLeft;\n \n int lessRight = query(rightTree, rating[i] - min - 1);\n int greaterRight = (n - i - 1) - lessRight;\n \n count += lessLeft * greaterRight + greaterLeft * lessRight;\n \n update(leftTree, rating[i] - min, 1);\n }\n \n return count;\n }\n\n private void update(int[] tree, int index, int value) {\n index++;\n while (index < tree.length) {\n tree[index] += value;\n index += index & (-index);\n }\n }\n\n private int query(int[] tree, int index) {\n int sum = 0;\n index++;\n while (index > 0) {\n sum += tree[index];\n index -= index & (-index);\n }\n return sum;\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n int numTeams(vector<int>& ratings) {\n // Find the maximum rating\n int maxRating = 0;\n for (int rating : ratings) {\n maxRating = max(maxRating, rating);\n }\n\n // Initialize Binary Indexed Trees for left and right sides\n vector<int> leftBIT(maxRating + 1, 0);\n vector<int> rightBIT(maxRating + 1, 0);\n\n // Populate the right BIT with all ratings initially\n for (int rating : ratings) {\n updateBIT(rightBIT, rating, 1);\n }\n\n int teams = 0;\n for (int currentRating : ratings) {\n // Remove current rating from right BIT\n updateBIT(rightBIT, currentRating, -1);\n\n // Count soldiers with smaller and larger ratings on both sides\n int smallerRatingsLeft = getPrefixSum(leftBIT, currentRating - 1);\n int smallerRatingsRight = getPrefixSum(rightBIT, currentRating - 1);\n int largerRatingsLeft = getPrefixSum(leftBIT, maxRating) -\n getPrefixSum(leftBIT, currentRating);\n int largerRatingsRight = getPrefixSum(rightBIT, maxRating) -\n getPrefixSum(rightBIT, currentRating);\n\n // Count increasing and decreasing sequences\n teams += (smallerRatingsLeft * largerRatingsRight);\n teams += (largerRatingsLeft * smallerRatingsRight);\n\n // Add current rating to left BIT\n updateBIT(leftBIT, currentRating, 1);\n }\n\n return teams;\n }\n\nprivate:\n // Update the Binary Indexed Tree\n void updateBIT(vector<int>& BIT, int index, int value) {\n while (index < BIT.size()) {\n BIT[index] += value;\n index +=\n index & (-index); // Move to the next relevant index in BIT\n }\n }\n\n // Get the sum of all elements up to the given index in the BIT\n int getPrefixSum(vector<int>& BIT, int index) {\n int sum = 0;\n while (index > 0) {\n sum += BIT[index];\n index -= index & (-index); // Move to the parent node in BIT\n }\n return sum;\n }\n};\n``` | 61 | 5 | ['Array', 'Dynamic Programming', 'Binary Indexed Tree', 'Python', 'C++', 'Java', 'Python3'] | 10 |
count-number-of-teams | Count left & right less or bigger->Fenwick Tree| Segment Tree||2ms Beats 99.79% | count-left-right-less-or-bigger-fenwick-wybfe | Intuition\n Describe your first thoughts on how to solve this problem. \nConsider the middle element in a 3-elemented valid team. Just consider counting how man | anwendeng | NORMAL | 2024-07-29T03:00:40.551018+00:00 | 2024-07-29T13:10:26.750397+00:00 | 8,902 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConsider the middle element in a 3-elemented valid team. Just consider counting how many bigger, smaller elements on his left & right sides.\n\nAn $O(n^2)$ solution is provided which is easy to implemented.\n\n1st time try to use Fenwick tree (binary indexed tree) to solve, so write it in OOP form.\nRef1: https://cp-algorithms.com/data_structures/fenwick.html\nRef2: https://cs.stackexchange.com/questions/10538/bit-what-is-the-intuition-behind-a-binary-indexed-tree-and-how-was-it-thought-a\n\n3rd solution uses segment tree.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The code is a nested for-loop. For each soldiert `i` (1<i<n-1) do the following.\n2. Set arrays `L[2], R[2]` containing the number of the bigger/smaller rating than i on the left & one right.\n3. Use loops to count for `L` & for `R`.\n4. Due to counting principle,`L[0]*R[1] + L[1]*R[0]` is the number of the valid teams for soldier i in the middle; add it to `cnt`.\n5. `cnt` is the answer\n6. 2nd solution uses BIT; in fact BIT has the efficient method to compute prefix sums which can perform fast. \n7. Segment tree is used as the 3rd approach.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2)$$\nFenwick tree: $O(n\\log m)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\nFenwick tree: $O(m)$\n# Code||C++ 21ms Beats 92.20%\n```\nclass Solution {\npublic:\n static int numTeams(vector<int>& rating) {\n const int n = rating.size();\n int cnt= 0;\n for (int i= 1; i < n-1; i++) {\n int L[2]={0}, R[2]={0};\n\n // Count ratings on the left of i\n for (int j = 0; j < i; j++) \n L[rating[j] < rating[i]]++;//rating is unique\n \n // Count ratings on the right of i\n for (int k=i+1; k<n; k++) \n R[rating[k] < rating[i]]++;\n\n // number of valid teams\n cnt += L[0]*R[1] + L[1]*R[0];\n }\n return cnt;\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n# C++ using Fenwick tree||2ms Beats 99.79%\nReplace update by add which is more suitable\n```\nstruct FenwickTree{\n vector<int> BIT;\n int n;\n FenwickTree(int n): n(n), BIT(n){}\n\n void add(int idx, int x){\n for (; idx<n; idx=idx|(idx+1))\n BIT[idx] += x;\n }\n\n int sum(int idx){// prefix sum\n int ans = 0;\n for (; idx>= 0; idx=(idx&(idx+1))-1)\n ans+=BIT[idx];\n return ans;\n }\n\n int sum(int l, int r){\n return sum(r)-sum(l-1);\n }\n};\n\nclass Solution {\npublic:\n static int numTeams(vector<int>& rating) {\n const int n=rating.size();\n const int m=*max_element(rating.begin(), rating.end());\n\n FenwickTree L(m+1), R(m+1);\n\n for(int x: rating) R.add(x, 1);\n\n int cnt=0;\n for(int x: rating){\n R.add(x, -1);// remove x from L\n\n int LLess=L.sum(x-1);\n int RLess=R.sum(x-1);\n int LBigger=L.sum(x+1, m);\n int RBigger=R.sum(x+1, m);\n\n cnt+=LLess*RBigger+LBigger*RLess;\n\n L.add(x, 1);// add x to L\n }\n return cnt;\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n# C++ using Segment tree||3ms Beats 99.68%\n```\nstruct SegmentTree {\n int n;\n vector<int> seg;\n\n SegmentTree(int n) : n(n), seg(2*n) {}\n\n void update(int i, int x) {\n i+=n;\n seg[i]+= x; // Increment the value at position i\n for (i>>= 1; i > 0; i>>= 1)\n seg[i] = seg[2*i] + seg[2*i+1];\n }\n\n int query(int l, int r) {\n int sum = 0;\n for (l+=n, r+=n; l <= r; l>>=1, r>>=1) {\n if (l&1) sum += seg[l++];\n if (!(r&1)) sum += seg[r--];\n }\n return sum;\n }\n};\n\nclass Solution {\npublic:\n static int numTeams(vector<int>& rating) {\n const int n=rating.size();\n const int m=*max_element(rating.begin(), rating.end());\n\n SegmentTree L(m+1), R(m+1);\n\n // Initialize R segment tree with the ratings\n for (int x : rating) R.update(x, 1);\n\n int cnt = 0;\n for (int x : rating) {\n R.update(x, -1); // Remove x from R\n\n int LLess=L.sum(x-1);\n int RLess=R.sum(x-1);\n int LBigger=L.sum(x+1, m);\n int RBigger=R.sum(x+1, m);\n\n cnt+=LLess*RBigger+LBigger*RLess;\n\n L.update(x, 1); // Add x to L\n }\n return cnt;\n }\n};\n\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n``` | 59 | 0 | ['Array', 'Bit Manipulation', 'Binary Indexed Tree', 'Segment Tree', 'Counting', 'Prefix Sum', 'C++'] | 10 |
count-number-of-teams | Java O(N^2) Very Simple 1D DP, 2 Pass | java-on2-very-simple-1d-dp-2-pass-by-mal-hmu5 | So basically we are employing the same technique as largest increasing/decreasing subsequence DP problem. For ith, we go back from i-1 to 0 and see how many ele | malayks | NORMAL | 2020-07-13T06:35:42.604419+00:00 | 2020-07-17T08:46:24.490593+00:00 | 7,095 | false | So basically we are employing the same technique as largest increasing/decreasing subsequence DP problem. For `ith`, we go back from `i-1` to `0` and see how many elements is `rating[i]` greater than, and we add the `DP[j]` to `count` for all `j < i` such that `rating[i] > rating[j]`. Why? Because we know that `rating[j]` is less than `rating[i]` and we also know that `rating[j]` is greater than `DP[j]` elements on it\'s left so they are also less than `rating[i]` hence they can form a combination. \n\nSimilarly we look for all `j < i` such that `rating[i] < rating[j]` during second pass for `rating[i] > rating[j] > rating[k]` combo.\n\n`DP[i]` is count of ratings less than `rating[i]` on it\'s left in first pass and count of ratings greater than `rating[i]` in second pass. Our answer is `count + DP[j]` for all `j < i` so that `rating[i] > rating[j]` during first pass and `rating[i] < rating[j]` during second pass.\n\nI have started my `j` loop at `i` because there are no duplicates hence for `j == i` nothing is gonna happen. It saved me trouble of checking `>=0` index check.\n```\nclass Solution {\n public int numTeams(int[] rating) {\n if(rating == null || rating.length == 0){\n return 0;\n }\n \n int len = rating.length;\n int[] dp = new int[len];\n int count = 0;\n \n // first <r[i] <r[j] <r[k] order\n for(int i = 0; i < len; i++){\n for(int j = i; j >= 0; j--){\n if(rating[i] > rating[j]){\n dp[i]++;\n count = count + dp[j];\n }\n }\n }\n \n //System.out.println(count);\n dp = new int[len];\n \n for(int i = 0; i < len; i++){\n for(int j = i; j >= 0; j--){\n if(rating[i] < rating[j]){\n dp[i]++;\n count = count + dp[j];\n }\n }\n }\n \n return count;\n \n }\n}\n``` | 56 | 1 | ['Dynamic Programming', 'Java'] | 8 |
count-number-of-teams | Python | clean DP solution O(n^2) 92 % fast | python-clean-dp-solution-on2-92-fast-by-uz6l4 | \nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n \n up = [0] * n\n down = [0] * n\n \ | leira0520 | NORMAL | 2020-09-22T18:25:47.081232+00:00 | 2020-09-22T18:25:55.951344+00:00 | 4,032 | false | ```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n \n up = [0] * n\n down = [0] * n\n \n teams = 0\n \n for i in range(n-1, -1, -1):\n for j in range(i+1, n):\n if rating[i] < rating[j]:\n up[i] += 1\n teams += up[j]\n else:\n down[i] += 1\n teams += down[j]\n \n return teams\n``` | 51 | 0 | ['Python3'] | 7 |
count-number-of-teams | C++ || O(n3) || 104 ms || O(n2) || 4 ms || Easy to understand | c-on3-104-ms-on2-4-ms-easy-to-understand-c8tq | Runtime: 104 ms, faster than 40.56% of C++ online submissions for Count Number of Teams.\nMemory Usage: 7.6 MB, less than 52.71% of C++ online submissions for C | anonymous_kumar | NORMAL | 2020-08-14T18:24:28.023940+00:00 | 2020-08-14T18:49:01.646398+00:00 | 4,854 | false | ***Runtime: 104 ms, faster than 40.56% of C++ online submissions for Count Number of Teams.\nMemory Usage: 7.6 MB, less than 52.71% of C++ online submissions for Count Number of Teams.***\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& r) {\n int n = r.size();\n int result = 0;\n for(int i = 0 ; i < n-2 ; i++){\n for(int j = i+1 ; j < n-1 ; j++){\n for(int k = j+1 ; k < n ; k++){\n if(((r[i] < r[j]) && (r[j] < r[k])) || ((r[i] > r[j]) && (r[j] > r[k]))){\n result++;\n }\n }\n }\n }\n return result;\n }\n};\n```\n***Runtime: 4 ms, faster than 98.59% of C++ online submissions for Count Number of Teams.\nMemory Usage: 7.5 MB, less than 93.78% of C++ online submissions for Count Number of Teams.***\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& arr) {\n int n = arr.size();\n int result = 0;\n for(int i = 1 ; i < n-1 ; i++){\n int leftSmall = 0, leftLarge = 0;\n int rightSmall = 0, rightLarge = 0;\n //left part\n for(int j = 0 ; j < i ; j++){\n if(arr[j] < arr[i]){\n leftSmall++;\n }\n if(arr[j] > arr[i]){\n leftLarge++;\n }\n }\n //right part\n for(int j = i+1 ; j < n ; j++){\n if(arr[j] < arr[i]){\n rightSmall++;\n }\n if(arr[j] > arr[i]){\n rightLarge++;\n }\n }\n result += leftSmall * rightLarge + leftLarge * rightSmall;\n }\n return result;\n }\n};\n``` | 50 | 3 | ['C', 'C++'] | 13 |
count-number-of-teams | BEATS 100%๐ฅ [ C++ / Py / Java / Go ] โ
SIMPLE | beats-100-c-py-java-go-simple-by-neoni_7-jvbs | Approach\n1. Initialize Counters: For each soldier at index i, initialize counters to count soldiers with ratings less than or greater than rating[i], both to t | Neoni_77 | NORMAL | 2024-07-29T05:13:33.787959+00:00 | 2024-07-29T05:13:33.787993+00:00 | 6,596 | false | # Approach\n1. **Initialize Counters:** For each soldier at index i, initialize counters to count soldiers with ratings less than or greater than rating[i], both to the left and right of i.\n\n2. **Count Soldiers:**\n - Traverse the array to count soldiers with ratings less than or greater than rating[i] to the right of i.\n - Traverse the array to count soldiers with ratings less than or greater than rating[i] to the left of i.\n3. **Calculate Valid Teams:** For each soldier i, the number of valid teams can be calculated as:\n- Teams with increasing order: right_less * left_more\n- Teams with decreasing order: right_more * left_less\n4. **Sum the Counts:** Sum these counts for all soldiers to get the total number of valid teams.\n\n```C++ []\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int total = 0;\n\n for ( int i = 0 ; i < rating.size() ; i ++ ){\n int right_less = 0 , right_more = 0 , left_less = 0 , left_more = 0;\n\n for ( int j = i + 1 ; j < rating.size() ; j ++ ){\n if ( rating[j] < rating[i] ) right_less++;\n else if ( rating[i] < rating[j] ) right_more++;\n }\n for ( int j = 0 ; j < i ; j ++ ){\n if ( rating[j] < rating[i] ) left_less++;\n else if ( rating[i] < rating[j] ) left_more ++;\n }\n\n total += right_less*left_more + right_more*left_less;\n }\n\n return total;\n }\n};\n```\n```python []\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n total = 0\n n = len(rating)\n \n for i in range(n):\n right_less = 0\n right_more = 0\n left_less = 0\n left_more = 0\n\n # Count soldiers after i\n for j in range(i + 1, n):\n if rating[j] < rating[i]:\n right_less += 1\n elif rating[j] > rating[i]:\n right_more += 1\n \n # Count soldiers before i\n for j in range(i):\n if rating[j] < rating[i]:\n left_less += 1\n elif rating[j] > rating[i]:\n left_more += 1\n\n # Calculate the total number of valid teams\n total += right_less * left_more + right_more * left_less\n\n return total\n\n```\n```Java []\nclass Solution {\n public int numTeams(int[] rating) {\n int total = 0;\n int n = rating.length;\n \n for (int i = 0; i < n; i++) {\n int rightLess = 0, rightMore = 0, leftLess = 0, leftMore = 0;\n\n // Count soldiers after i\n for (int j = i + 1; j < n; j++) {\n if (rating[j] < rating[i]) rightLess++;\n else if (rating[j] > rating[i]) rightMore++;\n }\n \n // Count soldiers before i\n for (int j = 0; j < i; j++) {\n if (rating[j] < rating[i]) leftLess++;\n else if (rating[j] > rating[i]) leftMore++;\n }\n\n // Calculate the total number of valid teams\n total += rightLess * leftMore + rightMore * leftLess;\n }\n\n return total;\n }\n}\n\n```\n```Go []\nfunc numTeams(rating []int) int {\n total := 0\n n := len(rating)\n \n for i := 0; i < n; i++ {\n rightLess, rightMore := 0, 0\n leftLess, leftMore := 0, 0\n // Count soldiers after i\n for j := i + 1; j < n; j++ {\n if rating[j] < rating[i] {\n rightLess++\n } else if rating[j] > rating[i] {\n rightMore++\n }\n } \n // Count soldiers before i\n for j := 0; j < i; j++ {\n if rating[j] < rating[i] {\n leftLess++\n } else if rating[j] > rating[i] {\n leftMore++\n }\n }\n // Calculate the total number of valid teams\n total += rightLess * leftMore + rightMore * leftLess\n }\n\n return total\n}\n```\n | 44 | 0 | ['C++', 'Java', 'Go', 'Python3'] | 5 |
count-number-of-teams | Greater and Smaller Array [Explained CPP/Python] O(n^2) time | greater-and-smaller-array-explained-cppp-9d3c | The idea is simple.\nAccording to Q we need three numbers A[i],A[j] and A[k] such that i<j<k and < < or > > property holds between the elements.\nFirst lets tak | srivastavaanshuman33 | NORMAL | 2020-03-29T04:14:16.937178+00:00 | 2021-06-26T17:50:14.233533+00:00 | 2,840 | false | The idea is simple.\nAccording to Q we need three numbers A[i],A[j] and A[k] such that i<j<k and < < or > > property holds between the elements.\n**First lets take A[i]>A[j]>A[k]**\nConsider the middle element if any element of the array will be the part of triplet and if we want it in middle then there should be at least one greater element present on right side of it and at least one smaller element on left of it.\n\n##### So total triplets with A[j] in middle will be (count of elements>A[j] on left) * (count of elements <A[j] on right) \n\nThus we make two arrays Greater and Smaller which will store count of elements greater than A[i] and smaller than A[i] in greater[i] and smaller[i] respectively.\n\n**Now for A[i]<A[j]<A[k] reverse the array and do the same thing**\n\n**CPP Version**\n```\n\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n=rating.size();\n int k= count(rating); // for < < case\n reverse(rating.begin(),rating.end());\n k+=(count(rating)); // for > > case\n return k;\n \n }\n \n int count(vector<int>& rating){\n int n=rating.size();\n vector<int> greater(n); //greater [i] store count of elements greater than rating[i] on right side\n vector<int> smaller(n); // smaller [i] stores count of elements smaller than rating[i] on left side\n for(int i=0;i<n;i++){\n int target=rating[i];\n int c=0;\n for(int j=i+1;j<n;j++){\n if(rating[j]>target)\n c++;\n }\n greater[i]=c;\n }\n \n for(int i=0;i<n;i++){\n int target=rating[i];\n int c=0;\n for(int j=i-1;j>=0;j--){\n if(rating[j]<target)\n c++;\n }\n smaller[i]=c;\n } \n int sum=0;\n for(int i=0;i<n;i++)\n sum+=(greater[i]*smaller[i]); //Total triplets with A[i] as middle element in ( >A[i] > ) this case\n return sum;\n \n }\n};\n```\n\n**Python Version**\n```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n def count(rating):\n n= len(rating)\n gre= [0]*n\n sm= [0]*n\n for (i,ele) in enumerate(rating):\n c=0\n for x in range(n-1,i,-1):\n if rating[x]>ele:\n c+=1\n gre[i]=c\n c=0\n for x in range(0,i):\n if rating[x]<ele:\n c+=1\n sm[i]=c\n ans=0\n for i in range(n):\n ans+=(gre[i]*sm[i])\n return ans;\n \n ans=0\n ans+=count(rating)\n rating.reverse()\n ans+=count(rating)\n return ans\n\t```\n**PLEASE UPVOTE IF YOU LIKE** | 33 | 1 | ['C++'] | 6 |
count-number-of-teams | Java solution with explanation | java-solution-with-explanation-by-201841-8nh8 | Here,we are traversing the array from 1st index to 2nd last index. Inside the loop ,we are tracking the elements which are greater or less on each side.\nSince | 20184152 | NORMAL | 2021-06-12T01:31:31.937509+00:00 | 2021-09-24T15:15:59.829054+00:00 | 2,949 | false | Here,we are traversing the array from 1st index to 2nd last index. Inside the loop ,we are tracking the elements which are greater or less on each side.\nSince two pattern selection are possible,so the no. of elements less than the current element and greater than the current will give no. of accending pattern. Similarly the descending one!\n\n```\nclass Solution {\n public int numTeams(int[] rating) {\n int n=rating.length;\n \n int total=0;\n for(int i=1;i<n-1;i++){\n int leftless=0; // for accending pattern\n int rightgreater=0; // for accending pattern\n \n int leftgreater=0; // for descending pattern\n int rightless=0; //for descending pattern\n \n for(int j=i-1;j>=0;j--){\n if(rating[i]>rating[j]){\n leftless++;\n }\n else{\n leftgreater++;\n }\n }\n for(int j=i+1;j<n;j++){\n if(rating[i]>rating[j]){\n rightless++;\n }else{\n rightgreater++;\n }\n }\n total+= leftless*rightgreater + rightless*leftgreater; // no of counts possible from the ith index.\n }\n return total;\n }\n}\n```\n **Hope you understand! Do upvote if you find it helpful!** | 32 | 1 | ['Java'] | 6 |
count-number-of-teams | [Python/Java] O(n^2) Easy to understand solution | pythonjava-on2-easy-to-understand-soluti-jzxw | The ides of this solution is to fix the middle one(pivot) and count the left ones which are less/greater than the pivot. After that we can update the combinatio | justin801514 | NORMAL | 2020-03-29T17:24:45.399462+00:00 | 2020-03-29T17:30:33.634509+00:00 | 3,811 | false | The ides of this solution is to fix the middle one(pivot) and count the left ones which are less/greater than the pivot. After that we can update the combination with `left` * `right`.\n\nExample:\n`rating` = `[2,1,3,4,7,6,8]`\n\nwhen `pivot = 4`, `less = [3, 3]`, then we can count the total combination of `(x, 4, x)` is 9 in ascending order.\nOn the other hand, `greater[0, 0]` will represent the descending order but in this case the total combination of this order is 0.\n\n**Python**\n```python\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n res = 0\n for i in range(1, len(rating) - 1):\n less, greater = [0, 0], [0, 0]\n for j in range(i):\n if rating[j] < rating[i]:\n less[0] += 1\n else:\n greater[0] += 1\n \n for k in range(i+1, len(rating)):\n if rating[i] < rating[k]:\n less[1] += 1\n else:\n greater[1] += 1\n res += less[0] * less[1] + greater[0] * greater[1]\n return res\n```\n\n**Java**\n```\nclass Solution {\n public int numTeams(int[] rating) {\n int res = 0;\n for (int i = 1; i < rating.length - 1; i++) {\n int[] less = new int[2], greater = new int[2];\n for (int j = 0; j < i; j++) {\n if (rating[j] < rating[i]) {\n less[0]++;\n } else {\n greater[0]++;\n }\n }\n \n for (int k = i + 1; k < rating.length; k++) {\n if (rating[i] < rating[k]) {\n less[1]++;\n } else {\n greater[1]++;\n }\n }\n res += less[0] * less[1] + greater[0] * greater[1];\n }\n return res;\n }\n}\n``` | 27 | 0 | ['Python', 'Java'] | 9 |
count-number-of-teams | ๐ฅAll Approaches you can tell in an Interview ๐ฅ | all-approaches-you-can-tell-in-an-interv-zcob | Approaches\nAll of them are pretty self explanatory and easy to understand if you are familiar with all the ds and algo used\n\n# Memoization\n\nclass Solution | bhavik_11 | NORMAL | 2024-07-29T09:25:52.279878+00:00 | 2024-07-29T09:25:52.279977+00:00 | 2,789 | false | # Approaches\nAll of them are pretty self explanatory and easy to understand if you are familiar with all the ds and algo used\n\n# Memoization\n```\nclass Solution {\nprivate:\n int dpi[1000][3];\n int fi(int idx, int cnt, vector<int> &rating) {\n // base cases\n if(cnt == 3) return 1;\n if(dpi[idx][cnt] != -1) return dpi[idx][cnt];\n\n int res = 0;\n for(int i=idx+1; i<rating.size(); ++i) {\n if(rating[i] <= rating[idx]) continue;\n res += fi(i, cnt+1, rating);\n }\n return dpi[idx][cnt] = res;\n }\n int dpd[1000][3];\n int fd(int idx, int cnt, vector<int> &rating) {\n // base cases\n if(cnt == 3) return 1;\n if(dpd[idx][cnt] != -1) return dpd[idx][cnt];\n\n int res = 0;\n for(int i=idx+1; i<rating.size(); ++i) {\n if(rating[i] >= rating[idx]) continue;\n res += fd(i, cnt+1, rating);\n }\n return dpd[idx][cnt] = res;\n }\npublic:\n int numTeams(vector<int>& rating) {\n int res = 0;\n memset(dpi, -1, sizeof(dpi));\n memset(dpd, -1, sizeof(dpd));\n for(int i=0; i<rating.size(); ++i) {\n res += fi(i,1,rating);\n res += fd(i,1,rating);\n }\n return res;\n }\n};\n```\n## Complexity\n- Time complexity: $$O(n*n)$$ \n\n- Space complexity: $$O(n)$$\n\n# Tabulation\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n vector<vector<int>> dpi(n, vector<int>(4,0));\n vector<vector<int>> dpd(n, vector<int>(4,0));\n\n // base case\n for(int i=0;i<n;++i) dpi[i][3] = dpd[i][3] = 1;\n \n for(int cnt=2; cnt>0; --cnt) {\n for(int idx=0; idx<n; ++idx) {\n int res1 = 0;\n int res2 = 0;\n for(int i=idx+1; i<n; ++i) {\n if(rating[i] > rating[idx]) res1 += dpi[i][cnt+1];\n if(rating[i] < rating[idx]) res2 += dpd[i][cnt+1];\n }\n dpi[idx][cnt] = res1;\n dpd[idx][cnt] = res2;\n }\n }\n\n int res = 0;\n for(int i=0; i<n; ++i) {\n res += dpi[i][1];\n res += dpd[i][1];\n }\n return res;\n }\n};\n```\n## Complexity\n- Time complexity: $$O(n*n)$$ \n\n- Space complexity:$$O(n)$$\n\n# Greedy\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n int res = 0;\n for(int j=1; j<n-1; ++j) {\n int lefti = 0;\n int leftd = 0;\n for(int i=0; i<j; ++i) {\n lefti += (rating[i] < rating[j]);\n leftd += (rating[i] > rating[j]);\n }\n int righti = 0;\n int rightd = 0;\n for(int k=j+1; k<n; ++k) {\n righti += (rating[j] < rating[k]);\n rightd += (rating[j] > rating[k]);\n }\n res += lefti * righti + leftd * rightd;\n }\n return res;\n }\n};\n```\n## Complexity\n- Time complexity: $$O(n*n)$$ \n\n- Space complexity:$$O(1)$$\n\n# Range Query DS (Segment Tree)\n```\n#define ll int\n// My Segment Tree Template (inspired from Pashka)\nclass item {\n public:\n ll val;\n \n item() {\n val = 0;\n }\n \n item(ll v) {\n val = v;\n }\n};\n \nclass SegTree {\n public:\n ll size;\n vector<item> values;\n \n item NEUTRAL_ELEMENT = item();\n \n item merge(item l,item r) {\n return item(l.val + r.val);\n }\n \n item single(ll v) {\n return item(v);\n }\n \n void init(ll n) {\n size = 1;\n while(size < n) size *= 2; //for last level array with some extra nodes for complete binary tree\n values.resize(2*size -1); //for complete binary tree\n }\n \n void build(vector<int> &a,ll x,ll lx,ll rx) {\n //base case\n if(rx-lx == 1) {\n if(lx < int(a.size())) {\n values[x] = single(a[lx]);\n }\n return; \n }\n \n ll m = (lx+rx)/2;\n build(a,2*x +1,lx,m);\n build(a,2*x +2,m,rx);\n values[x] = merge(values[2*x +1],values[2*x +2]);\n }\n \n void build(vector<int> &a) {\n build(a,0,0,size);\n }\n \n void set(ll i,ll v,ll x,ll lx,ll rx) {\n //base case\n if(rx-lx == 1) {\n values[x] = single(v);\n return;\n }\n \n ll m = (lx+rx)/2;\n if(i < m) {\n set(i,v,2*x +1,lx,m);\n }\n else {\n set(i,v,2*x +2,m,rx);\n }\n values[x] = merge(values[2*x+1],values[2*x+2]);\n }\n \n void set(ll i,ll v) {\n set(i,v,0,0,size);\n }\n\n item calc(ll l,ll r,ll x,ll lx,ll rx) {\n //base cases\n if(lx >= r || l >= rx) return NEUTRAL_ELEMENT;\n if(lx >= l && rx <= r) return values[x];\n \n ll m = (lx+rx)/2;\n item s1 = calc(l,r,2*x+1,lx,m);\n item s2 = calc(l,r,2*x+2,m,rx);\n return merge(s1,s2);\n } \n \n item query(ll l,ll r) {\n return calc(l,r+1,0,0,size);\n }\n};\n\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int mx = 1e5;\n SegTree st1, st2;\n st1.init(mx), st2.init(mx);\n \n int n = rating.size();\n for(int i=0; i<n; ++i) st2.set(rating[i], 1);\n\n int res = 0;\n for(int i=0; i<n; ++i) {\n int lefti = st1.query(0,rating[i]-1).val;\n int leftd = st1.query(rating[i]+1,mx).val;\n int righti = st2.query(rating[i]+1,mx).val - leftd;\n int rightd = st2.query(0,rating[i]-1).val - lefti;\n st1.set(rating[i], 1);\n res += lefti * righti + leftd * rightd;\n }\n return res;\n\n }\n};\n```\n## Complexity\n- Time complexity: $$O(n*log(mx))$$ \n\n- Space complexity:$$O(mx)$$\n\n\n# PBDS\n```\n// PBDS template starts\n\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/detail/standard_policies.hpp>\n#include <functional>\nusing namespace __gnu_pbds;\n\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\n// ordered_set st; (use less_equal for multiset else use less for set)\n// st.order_of_key(k); Returns the number of elements strictly smaller than k.\n// st.find_by_order(k); Returns the address of the element at kth index in the set while using zero-based indexing\n// Each of these operations has a time complexity of O(log2(n))\n\n// PBDS template ends\n\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n ordered_set st1, st2;\n int n = rating.size();\n for(int i=0; i<n; ++i) st2.insert(rating[i]);\n \n int res = 0;\n for(int i=0; i<n; ++i) {\n int lefti = st1.order_of_key(rating[i]);\n int leftd = st1.size() - lefti;\n st1.insert(rating[i]);\n\n st2.erase(rating[i]);\n int rightd = st2.order_of_key(rating[i]);\n int righti = st2.size() - rightd;\n\n res += lefti * righti + leftd * rightd;\n } \n return res;\n }\n};\n```\n## Complexity\n- Time complexity: $$O(n*log(n))$$ \n\n- Space complexity:$$O(n)$$\n\n\n\n\n**Hope you found this helpful\nIf so please do Upvote it\nHappy Coding!!**\n\n\n\n | 26 | 0 | ['Dynamic Programming', 'Greedy', 'Segment Tree', 'Ordered Set', 'C++'] | 1 |
count-number-of-teams | C++ Simple logic with detailed explanation | c-simple-logic-with-detailed-explanation-l4ra | Explanation:\nWhile going through loop from 2nd element to n-1 we just trying to find out how many elements are greater or less than at the left side of the ele | rebel_roar | NORMAL | 2021-06-29T04:27:41.051966+00:00 | 2021-07-26T07:37:48.468658+00:00 | 1,744 | false | **Explanation:**\nWhile going through loop from 2nd element to n-1 we just trying to find out how many elements are greater or less than at the left side of the element and how many element are less or greater than the element at his right side.\nAnd calculate the teams by using this logic.\n```teams += (leftLess*rightGreater) + (leftGreater*rightLess)```\n\n**Intiution behind the logic**\n\tFor better understanding Let\'s take an example : [2,5,3,4,1]\n\t\nSo if we wanted to make a team **including 3** then we just need to find the **one less or greater element at the left of 3 and one less or greater element at the right of 3** as mention in the problem statement:\n(consider rating[j] as a current element here current element is 3)\n\t\t(```(rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n)```)\n\t\t\tHere if we count all the parameters written above for ```3``` then \n\t\t\tleftLess = 1;\n\t\t\tleftGreater = 1;\n\t\t\trightLess = 1;\n\t\t\trightGreater = 1;\n\t\t\nFor 3 we have 1 element leftLess and 1 element rightGreater (2 < 3 < 4) so we can make a team and also we have 1 element rightLess and 1 element leftGreater (5 > 3 > 1) and this is also a valid team so now we have 2 teams in which 3 is member.\n\nSo ```(leftLess*rightGreater)``` this term is for if we have more than 1 less element at left and greater element at right of the element (Because all these element can make a seperate team with current element) and ```(leftGreater*rightLess)``` for this term if we have more than 1 greater element at the left of the current element and 1 less element at the right of the currrent element (These can also make a seperate team including current element) and at last i am adding both terms because both ways are valid to make a team.\n\nSo by using this logic we calculate for all the element and added in variable and at last return this.\n```\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n int teams = 0;\n for(int u=1;u<n-1;u++){\n int leftLess=0,leftGreater=0,rightLess=0,rightGreater=0;\n for(int j=0;j<u;j++){\n if(rating[j]>rating[u])leftGreater++;\n else leftLess++;\n }\n for(int j=u+1;j<n;j++){\n if(rating[j]>rating[u])rightGreater++;\n else rightLess++;\n }\n teams += (leftLess*rightGreater) + (leftGreater*rightLess);\n }\n return teams;\n }\n```\nTime comlexity : O(n^2) | 26 | 0 | ['C', 'C++'] | 1 |
count-number-of-teams | C++ || O(n^2) || Recursion || Memoization Solution || DP | c-on2-recursion-memoization-solution-dp-9wlui | We will consider every element as starting element than call the recursive function.\nSince its the first element we have not decided that will it be increasing | utkarsh_b | NORMAL | 2022-02-02T05:48:46.648577+00:00 | 2022-02-02T05:52:48.545589+00:00 | 2,135 | false | We will consider every element as starting element than call the recursive function.\nSince its the first element we have not decided that will it be increasing or decreasing sequence.\nSo,\n1. state=0 :-means we have not decided is it a increasing or decreasing we will consider both conditions\n```\n if(ele<rating[i]) ans+=solve(i,taken+1,1,rating);\n else if(ele>rating[i]) ans+=solve(i,taken+1,2,rating);\n```\n\n2. state=1 :- mean it increasing sequence and we have to search element greater than the current.\n```\n if(ele<rating[i]) ans+=solve(i,taken+1,1,rating);\n```\n3. state=2 :- means its a decreasing sequence and we have to search element less than the current\n ```\n if(ele>rating[i]) ans+=solve(i,taken+1,2,rating);\n```\ntaken :- the number of element we have taken in the sequence.\n\nSo the Complexity is O(n*(n*(3*(4)))=> O(n^2).\n```\nclass Solution {\npublic:\n int dp[1001][4][3];\n int solve(int idx,int taken,int state,vector<int> &rating){\n int n=rating.size();\n if(taken==3) return 1;\n if(dp[idx][taken][state]!=-1) return dp[idx][taken][state];\n \n int ans=0,ele=rating[idx];\n for(int i=idx+1;i<n;i++){\n if(state==0){\n if(ele<rating[i]) ans+=solve(i,taken+1,1,rating);\n else if(ele>rating[i]) ans+=solve(i,taken+1,2,rating);\n }\n else if(state==1){\n if(ele<rating[i]) ans+=solve(i,taken+1,1,rating);\n }\n else if(state==2){\n if(ele>rating[i]) ans+=solve(i,taken+1,2,rating);\n }\n }\n return dp[idx][taken][state]=ans;\n }\n int numTeams(vector<int>& rating) {\n int ans=0,n=rating.size();\n memset(dp,-1,sizeof(dp));\n \n for(int i=0;i<=n-3;i++){\n ans+=solve(i,1,0,rating);\n }\n return ans;\n }\n};\n``` | 24 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'C'] | 4 |
count-number-of-teams | Python Solution | python-solution-by-a_bs-u366 | Code\n\nfrom typing import List\n\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n count = 0\n \n | 20250406.A_BS | NORMAL | 2024-07-29T02:53:48.778392+00:00 | 2024-07-29T02:53:48.778425+00:00 | 2,801 | false | # Code\n```\nfrom typing import List\n\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n count = 0\n \n for j in range(n):\n leftLess = leftGreater = rightLess = rightGreater = 0\n\n for i in range(j):\n if rating[i] < rating[j]:\n leftLess += 1\n elif rating[i] > rating[j]:\n leftGreater += 1\n \n for k in range(j + 1, n):\n if rating[k] < rating[j]:\n rightLess += 1\n elif rating[k] > rating[j]:\n rightGreater += 1\n \n count += leftLess * rightGreater + leftGreater * rightLess\n \n return count\n\n```\n `rating = [2, 5, 3, 4, 1]` \n\n### Step-by-Step Execution \n\n1. **Initialize the class and method:**\n\n```python\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n count = 0\n```\n\n2. **Loop through each soldier as the middle soldier `j`:**\n\n```python\n for j in range(n):\n leftLess = leftGreater = rightLess = rightGreater = 0\n```\n\n3. **For each `j`, count the soldiers before and after `j`:**\n\nLet\'s go through each iteration in detail:\n\n### Iteration 1: `j = 0` (rating[0] = 2)\n- **Left counts** (None, as there are no elements before index 0):\n - `leftLess = 0`\n - `leftGreater = 0`\n\n- **Right counts**:\n - `rating[1] = 5` (greater than 2): `rightGreater = 1`\n - `rating[2] = 3` (greater than 2): `rightGreater = 2`\n - `rating[3] = 4` (greater than 2): `rightGreater = 3`\n - `rating[4] = 1` (less than 2): `rightLess = 1`\n\n- **Calculate valid teams**:\n - `count += leftLess * rightGreater + leftGreater * rightLess = 0 * 3 + 0 * 1 = 0`\n\n### Iteration 2: `j = 1` (rating[1] = 5)\n- **Left counts**:\n - `rating[0] = 2` (less than 5): `leftLess = 1`\n\n- **Right counts**:\n - `rating[2] = 3` (less than 5): `rightLess = 1`\n - `rating[3] = 4` (less than 5): `rightLess = 2`\n - `rating[4] = 1` (less than 5): `rightLess = 3`\n\n- **Calculate valid teams**:\n - `count += leftLess * rightGreater + leftGreater * rightLess = 1 * 0 + 0 * 3 = 0`\n\n### Iteration 3: `j = 2` (rating[2] = 3)\n- **Left counts**:\n - `rating[0] = 2` (less than 3): `leftLess = 1`\n - `rating[1] = 5` (greater than 3): `leftGreater = 1`\n\n- **Right counts**:\n - `rating[3] = 4` (greater than 3): `rightGreater = 1`\n - `rating[4] = 1` (less than 3): `rightLess = 1`\n\n- **Calculate valid teams**:\n - `count += leftLess * rightGreater + leftGreater * rightLess = 1 * 1 + 1 * 1 = 2`\n\n### Iteration 4: `j = 3` (rating[3] = 4)\n- **Left counts**:\n - `rating[0] = 2` (less than 4): `leftLess = 1`\n - `rating[1] = 5` (greater than 4): `leftGreater = 1`\n - `rating[2] = 3` (less than 4): `leftLess = 2`\n\n- **Right counts**:\n - `rating[4] = 1` (less than 4): `rightLess = 1`\n\n- **Calculate valid teams**:\n - `count += leftLess * rightGreater + leftGreater * rightLess = 2 * 0 + 1 * 1 = 1`\n\n### Iteration 5: `j = 4` (rating[4] = 1)\n- **Left counts**:\n - `rating[0] = 2` (greater than 1): `leftGreater = 1`\n - `rating[1] = 5` (greater than 1): `leftGreater = 2`\n - `rating[2] = 3` (greater than 1): `leftGreater = 3`\n - `rating[3] = 4` (greater than 1): `leftGreater = 4`\n\n- **Right counts** (None, as there are no elements after index 4):\n - `rightLess = 0`\n - `rightGreater = 0`\n\n- **Calculate valid teams**:\n - `count += leftLess * rightGreater + leftGreater * rightLess = 0 * 0 + 4 * 0 = 0`\n\n### Final count:\n\nAdding up all the counts from each iteration, we get `0 + 0 + 2 + 1 + 0 = 3`.\n\n4. **Return the final count:**\n\n```python\n return count\n```\n | 23 | 1 | ['Python3'] | 7 |
count-number-of-teams | [C++] O(n^2) count | c-on2-count-by-zhanghuimeng-yrgx | Find all the triplets in an rating array that satisfiy i<j<k and rating[i]<rating[j]<rating[k] or i<j<k and rating[i]>rating[j]>rating[k].\n\n# Explanation\n\nB | zhanghuimeng | NORMAL | 2020-03-29T04:02:46.742824+00:00 | 2020-03-29T04:42:06.256507+00:00 | 1,696 | false | Find all the triplets in an `rating` array that satisfiy `i<j<k` and `rating[i]<rating[j]<rating[k]` or `i<j<k` and `rating[i]>rating[j]>rating[k]`.\n\n# Explanation\n\nBecause `n` is small (only 200), an O(n^3) algorithm is ok. But it is easy to optimize the algorithm to O(n^2). For each `rating[j]`, the number of triplets satisfying `i<j<k` and `rating[i]<rating[j]<rating[k]` is `cnt(i<j, rating[i]<rating[j]) * cnt(j<k, rating[j]<rating[k])`, and the number of triplets satisfying `i<j<k` and `rating[i]>rating[j]>rating[k]` is `cnt(i<j, rating[i]>rating[j]) * cnt(j<k, rating[j]>rating[k])`.\n\n# C++ Solution\n\n```cpp\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n int ans = 0;\n for (int i = 0; i < n; i++) {\n int leftLarger = 0, leftSmaller = 0, rightLarger = 0, rightSmaller = 0;\n for (int j = 0; j < i; j++)\n if (rating[j] < rating[i])\n leftSmaller++;\n else if (rating[j] > rating[i])\n leftLarger++;\n for (int j = i + 1; j < n; j++)\n if (rating[j] < rating[i])\n rightSmaller++;\n else if (rating[j] > rating[i])\n rightLarger++;\n ans += leftSmaller * rightLarger + leftLarger * rightSmaller;\n }\n return ans;\n }\n};\n```\n | 23 | 0 | [] | 3 |
count-number-of-teams | Easy & Clear Solution C++ 0ms(100%) | easy-clear-solution-c-0ms100-by-moazmar-zd4y | \nclass Solution {\npublic:\n Solution(){\n ios::sync_with_stdio(0); cout.tie(0); cin.tie(0);\n }\n int numTeams(vector<int>& rating) {\n | moazmar | NORMAL | 2021-01-08T14:35:18.361892+00:00 | 2021-01-08T14:35:18.361932+00:00 | 2,448 | false | ```\nclass Solution {\npublic:\n Solution(){\n ios::sync_with_stdio(0); cout.tie(0); cin.tie(0);\n }\n int numTeams(vector<int>& rating) {\n int n=rating.size(),res=0,rightLess,rightGreat,leftLess,leftGreat;\n if(n<3)return 0;\n for(int i=1;i<n-1;i++){\n rightLess=0;rightGreat=0; leftLess=0; leftGreat=0;\n for(int j=0;j<i;j++){\n if(rating[j]<rating[i])leftLess++;\n else leftGreat++;\n } \n for(int j=i+1;j<n;j++){\n if(rating[j]>rating[i])rightGreat++;\n else rightLess++;\n }\n res=res+leftLess*rightGreat + leftGreat*rightLess;\n }\n return res;\n }\n};\n``` | 19 | 2 | ['C', 'C++'] | 4 |
count-number-of-teams | ๐ผ Beats 96.63% (14ms)๐ฅ | 3 Solutions | โ
| beats-9663-14ms-3-solutions-by-b_i_t-ua3n | \n\n# Solution 1: Brute Force\n- Complexity:\n - Time: O(n^3)\n - Space: O(1)\n# Code\nC++ []\nclass Solution {\npublic:\n int numTeams(vector<int>& ra | B_I_T | NORMAL | 2024-07-29T06:21:48.384525+00:00 | 2024-07-29T06:22:40.443904+00:00 | 2,289 | false | \n\n# Solution 1: Brute Force\n- Complexity:\n - Time: O(n^3)\n - Space: O(1)\n# Code\n```C++ []\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int res = 0;\n for(int i=0; i<rating.size()-2; i++){\n for(int j=i+1; j<rating.size()-1; j++){\n for(int k=j+1; k<rating.size(); k++){\n if(rating[i] > rating[j] && rating[j] > rating[k]){\n res++;\n }\n if(rating[i] < rating[j] && rating[j] < rating[k]){\n res++;\n }\n }\n }\n }\n return res;\n }\n}; \n```\n```Java []\nclass Solution {\n public int numTeams(int[] rating) {\n int res = 0;\n for (int i = 0; i < rating.length - 2; i++) {\n for (int j = i + 1; j < rating.length - 1; j++) {\n for (int k = j + 1; k < rating.length; k++) {\n if ((rating[i] < rating[j] && rating[j] < rating[k]) || (rating[i] > rating[j] && rating[j] > rating[k])) {\n res++;\n }\n }\n }\n }\n return res;\n }\n}\n```\n```Python []\n# TLE\nclass Solution(object):\n def numTeams(self, rating):\n res = 0\n n = len(rating)\n for i in range(n - 2):\n for j in range(i + 1, n - 1):\n for k in range(j + 1, n):\n if (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]):\n res += 1\n return res\n \n```\n```Javascript []\n// TLE\nvar numTeams = function(rating) {\n let res = 0;\n for (let i = 0; i < rating.length - 2; i++) {\n for (let j = i + 1; j < rating.length - 1; j++) {\n for (let k = j + 1; k < rating.length; k++) {\n if ((rating[i] < rating[j] && rating[j] < rating[k]) || (rating[i] > rating[j] && rating[j] > rating[k])) {\n res++;\n }\n }\n }\n }\n return res;\n};\n```\n# Solution 2: Adjacency Lists\n\n# Intuition\nUse adjacency lists to store pairs of ratings where one is greater or less than the other. Then use these lists to count the number of valid triplets.\n# Approach\n- Create two adjacency lists to store ratings that are greater or less than the current rating.\n- Iterate through the ratings and count the number of valid triplets using the adjacency lists.\n# Complexity\n- Time: O(n*n)\n- Space: O(n*n)\n# Code\n```C++ []\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int maxi = 0;\n for(const int & i : rating){\n maxi = max(maxi,i);\n }\n vector<vector<int>> adj1(maxi+1),adj2(maxi+1);\n for(int i=0; i<rating.size(); i++){\n for(int j=i+1; j<rating.size(); j++){\n if(rating[i] > rating[j]){\n adj1[rating[i]].push_back(rating[j]);\n }else if(rating[i] < rating[j]){\n adj2[rating[i]].push_back(rating[j]);\n }\n }\n }\n int res = 0;\n for(const int & i : rating){\n for(const int & j : adj1[i])\n res += adj1[j].size();\n for(const int & j : adj2[i])\n res += adj2[j].size();\n }\n\n return res;\n }\n};\n```\n```Java []\nclass Solution {\n public int numTeams(int[] rating) {\n int n = rating.length;\n int maxRating = 0;\n for (int r : rating) {\n maxRating = Math.max(maxRating, r);\n }\n List<Integer>[] adj1 = new List[maxRating + 1];\n List<Integer>[] adj2 = new List[maxRating + 1];\n for (int i = 0; i <= maxRating; i++) {\n adj1[i] = new ArrayList<>();\n adj2[i] = new ArrayList<>();\n }\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (rating[i] > rating[j]) {\n adj1[rating[i]].add(rating[j]);\n } else if (rating[i] < rating[j]) {\n adj2[rating[i]].add(rating[j]);\n }\n }\n }\n int res = 0;\n for (int r : rating) {\n for (int j : adj1[r]) {\n res += adj1[j].size();\n }\n for (int j : adj2[r]) {\n res += adj2[j].size();\n }\n }\n return res;\n }\n}\n```\n```Python []\nclass Solution(object):\n def numTeams(self, rating):\n n = len(rating)\n maxi = max(rating)\n adj1 = [[] for _ in range(maxi + 1)]\n adj2 = [[] for _ in range(maxi + 1)]\n \n for i in range(n):\n for j in range(i + 1, n):\n if rating[i] > rating[j]:\n adj1[rating[i]].append(rating[j])\n elif rating[i] < rating[j]:\n adj2[rating[i]].append(rating[j])\n \n res = 0\n for r in rating:\n for j in adj1[r]:\n res += len(adj1[j])\n for j in adj2[r]:\n res += len(adj2[j])\n \n return res\n```\n```Javascript []\nvar numTeams = function(rating) {\n let maxi = Math.max(...rating);\n let adj1 = Array.from({ length: maxi + 1 }, () => []);\n let adj2 = Array.from({ length: maxi + 1 }, () => []);\n \n for (let i = 0; i < rating.length; i++) {\n for (let j = i + 1; j < rating.length; j++) {\n if (rating[i] > rating[j]) {\n adj1[rating[i]].push(rating[j]);\n } else if (rating[i] < rating[j]) {\n adj2[rating[i]].push(rating[j]);\n }\n }\n }\n \n let res = 0;\n for (let r of rating) {\n for (let j of adj1[r]) {\n res += adj1[j].length;\n }\n for (let j of adj2[r]) {\n res += adj2[j].length;\n }\n }\n return res;\n};\n```\n# Solution 3: Counting with Prefix Sums\n\n# Intuition\nUse a single loop to iterate through each soldier\'s rating and count the number of valid soldiers on the left and right sides.\n# Approach\n- For each soldier, count the number of ratings less and greater on the left and right sides.\n- Use these counts to calculate the number of valid triplets.\n# Complexity\n- Time: O(n*n)\n- Space: O(1)\n# Code\n```C++ []\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int res = 0,n=rating.size();\n for(int i=1; i<n; i++){\n int ls,lg,rs,rg;\n ls = lg = rs = rg = 0;\n for(int j=0; j<i; j++){\n if(rating[j] < rating[i]) ls++;\n else lg++;\n }\n for(int j=i+1; j<n; j++){\n if(rating[j] < rating[i]) rs++;\n else rg++;\n }\n res += (ls*rg) + (rs*lg);\n }\n return res;\n }\n};\n\n```\n```Java []\nclass Solution {\n public int numTeams(int[] rating) {\n int res = 0, n = rating.length;\n for (int i = 1; i < n; i++) {\n int ls = 0, lg = 0, rs = 0, rg = 0;\n for (int j = 0; j < i; j++) {\n if (rating[j] < rating[i]) ls++;\n else lg++;\n }\n for (int j = i + 1; j < n; j++) {\n if (rating[j] < rating[i]) rs++;\n else rg++;\n }\n res += (ls * rg) + (rs * lg);\n }\n return res;\n }\n}\n```\n```Python []\nclass Solution(object):\n def numTeams(self, rating):\n res = 0\n n = len(rating)\n for i in range(1, n):\n ls = lg = rs = rg = 0\n for j in range(i):\n if rating[j] < rating[i]:\n ls += 1\n else:\n lg += 1\n for j in range(i + 1, n):\n if rating[j] < rating[i]:\n rs += 1\n else:\n rg += 1\n res += (ls * rg) + (rs * lg)\n return res\n```\n```Javascript []\nvar numTeams = function(rating) {\n let res = 0;\n let n = rating.length;\n \n for (let i = 1; i < n; i++) {\n let ls = 0, lg = 0, rs = 0, rg = 0;\n \n for (let j = 0; j < i; j++) {\n if (rating[j] < rating[i]) {\n ls++;\n } else {\n lg++;\n }\n }\n \n for (let j = i + 1; j < n; j++) {\n if (rating[j] < rating[i]) {\n rs++;\n } else {\n rg++;\n }\n }\n \n res += (ls * rg) + (rs * lg);\n }\n return res;\n};\n```\n\n | 17 | 0 | ['Array', 'Python', 'C++', 'Java', 'JavaScript'] | 2 |
count-number-of-teams | 5 lines of simple C++ understandable solution | 5-lines-of-simple-c-understandable-solut-g6my | \nint ans = 0;\n int numTeams(vector<int>& rating) {\n for (int i = 1 ; i < rating.size()-1 ;i++){\n int left_lesser = 0, left_greater=0, right_les | aynburnt | NORMAL | 2021-05-22T04:42:46.093802+00:00 | 2021-05-22T04:42:46.093848+00:00 | 1,091 | false | ```\nint ans = 0;\n int numTeams(vector<int>& rating) {\n for (int i = 1 ; i < rating.size()-1 ;i++){\n int left_lesser = 0, left_greater=0, right_lesser=0, right_greater=0;\n for(int j = i-1; j>=0; j--)if(rating[j] > rating[i])left_greater++;else left_lesser++;\n for(int j = i+1; j<rating.size(); j++)if(rating[j] > rating[i])right_greater++;else right_lesser++;\n ans+= left_lesser*right_greater + left_greater*right_lesser;\n }\n return ans;\n }\n```\n# plz upvote if you find it helpful | 17 | 6 | ['C'] | 1 |
count-number-of-teams | [Python] Fenwick tree O(NlogN) solution beats 99% | python-fenwick-tree-onlogn-solution-beat-sdtp | This solution is adapted from a similar C++ solution. Here\'s the basic idea:\n- fw and bw are two Fenwick trees.\n- fw.sum(i+1) returns the number of ratings l | m-just | NORMAL | 2020-10-04T09:06:09.714654+00:00 | 2020-10-04T09:26:21.301469+00:00 | 1,374 | false | This solution is adapted from a similar [C++ solution](https://leetcode.com/problems/count-number-of-teams/discuss/555196/C%2B%2B-solutions-O(n-3)-O(n-2)-and-O(nlogn)). Here\'s the basic idea:\n- `fw` and `bw` are two Fenwick trees.\n- `fw.sum(i+1)` returns the number of ratings less than `rating[i]` before `rating[i]`.\n- `bw.sum(N-i)` returns the number of ratings greater than `rating[i]` after `rating[i]`.\n- Iterate `ratings` and use every rating as the center pivot, then the number of increasing 3-tuples with pivot `ratings[i]` is simply `fw.sum(i+1) * bw.sum(N-i)`.\n- Similarly, the number of decreasing 3-tuples can be deduced from `fw.sum(i+1)` and `bw.sum(N-i)` since every rating is unique.\n```python\nclass FenwickTree: # a.k.a. Binary Index Tree (BIT)\n def __init__(self, N: int):\n self.N = N\n self.arr = [0] * N\n \n def sum(self, i: int): # i is 1-indexed\n s = 0\n while i:\n s += self.arr[i-1]\n i -= i & -i\n return s\n \n def add(self, i: int, k): # i is 1-indexed\n while i <= self.N:\n self.arr[i-1] += k\n i += i & -i\n \n\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n N = len(rating)\n fw = FenwickTree(N)\n bw = FenwickTree(N)\n \n r = sorted((n, i) for i, n in enumerate(rating))\n for n, i in reversed(r):\n bw.add(N-i, 1)\n \n ans = 0\n for n, i in r:\n bw.add(N-i, -1)\n a, b = fw.sum(i+1), bw.sum(N-i)\n ans += a * b + (i - a) * (N - i - b - 1)\n fw.add(i+1, 1)\n return ans\n```\nVote up if you think it\'s helpful, thanks! | 14 | 0 | ['Binary Tree', 'Python'] | 1 |
count-number-of-teams | JAVA Beats 100%, Clean Code Solution | java-beats-100-clean-code-solution-by-an-h5ih | \nclass Solution {\n public int numTeams(int[] rating) {\n \n int countTeams = 0;\n \n for (int i = 0; i < rating.length; i++) {\ | anii_agrawal | NORMAL | 2020-08-04T08:10:49.872073+00:00 | 2020-08-04T08:10:49.872127+00:00 | 1,506 | false | ```\nclass Solution {\n public int numTeams(int[] rating) {\n \n int countTeams = 0;\n \n for (int i = 0; i < rating.length; i++) {\n int lesserCount = 0;\n int greaterCount = 0;\n \n for (int j = 0; j < i; j++) {\n if (rating[i] > rating[j]) {\n ++lesserCount;\n }\n }\n \n for (int j = i + 1; j < rating.length; j++) {\n if (rating[i] < rating[j]) {\n ++greaterCount;\n }\n }\n \n countTeams += lesserCount * greaterCount;\n countTeams += (i - lesserCount) * (rating.length - 1 - i - greaterCount);\n }\n \n return countTeams;\n }\n}\n```\n\nPlease help to **UPVOTE** if this post is useful for you.\nIf you have any questions, feel free to comment below.\n**HAPPY CODING :)\nLOVE CODING :)**\n | 14 | 0 | [] | 4 |
count-number-of-teams | Java O(n^2) solution one pass | java-on2-solution-one-pass-by-arthur0455-l5or | According to the description, any three rating values must satisfy i < j < k and rating[i] < rating[j] < rating[k] or rating[i] > rating[j] > rating[k]. \nIf we | arthur0455 | NORMAL | 2020-07-12T16:28:41.127800+00:00 | 2020-07-13T08:01:42.462599+00:00 | 825 | false | According to the description, any three rating values must satisfy i < j < k and rating[i] < rating[j] < rating[k] or rating[i] > rating[j] > rating[k]. \nIf we select a value as rating[j] from the rating array, we only need to find rating values:\n* less than rating[j] and its index smaller than j as rating[i]\n* lager than rating[j] and its index lager than j as rating[k]\nor\n* less than rating[j] and its index lager than j as rating[i]\n* lager than rating[j] and its index smaller than j as rating[k].\n\n(in code, "less" or "lager" means values\' comparison, "before" or "after" means positions\' or indices\' comparison)\n\nAll team should meet the property that i < j < k. The first group rating values forms teams rating[i] < rating[j] < rating[k] and the second group forms teams rating[i] > rating[j] > rating[k].\n\nThe number of a rating value forming teams and being the middle value equals sum of the number of teams belong to the first and the second group.\n\nFor example,\n**Input:** rating = [2,5,3,4,1]\n1. 5 is rating[j], number of lessBefore is 1 (2) and number of lagerAfter is 0; number of lagerBefore is 0 and number of lessAfter is 3 (3, 4, 1). Number of teams in the first group is 0 and number of teams in the second group is 0. 0 teams can be formed when the value 5 is rating[j].\n2. 3 is rating[j], number of lessBefore is 1 (2) and number of lagerAfter is 1 (4); number of lagerBefore is 1 (5) and number of lessAfter is 1 (1). Number of teams in the first group is 1 and number of teams in the second group is 1. 2 teams can be formed when the value 5 is rating[j].\n3. 4 is rating[j], number of lessBefore is 2 (2, 3) and number of lagerAfter is 0; number of lagerBefore is 1 (5) and number of lessAfter is 1 (1). Number of teams in the first group is 0 and number of teams in the second group is 1. 1 team can be formed when the value 5 is rating[j].\n\nThe total number of teams can be formed based on the rating array is 3 (0 + 2 + 1 = 3).\n\n```\nclass Solution {\n public int numTeams(int[] rating) {\n int ans = 0, lagerAfter, lagerBefore, lessAfter, lessBefore;\n for(int i = 1; i < rating.length - 1; i++) {\n lagerAfter = lagerBefore = lessAfter = lessBefore = 0;\n for(int j = 0; j < rating.length; j++) {\n if(i == j) continue;\n if(rating[i] < rating[j]) {\n if(i < j) {\n lessBefore++;\n } else {\n lessAfter++;\n }\n } else {\n if(i < j) {\n lagerBefore++;\n } else {\n lagerAfter++;\n }\n }\n }\n ans += lagerAfter * lessBefore + lagerBefore * lessAfter;\n }\n return ans;\n }\n}\n``` | 13 | 2 | [] | 1 |
count-number-of-teams | Java || Simple || O(n2) Easy to understand | java-simple-on2-easy-to-understand-by-ri-llrf | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Ridwan03 | NORMAL | 2024-07-29T02:58:57.903652+00:00 | 2024-07-29T02:58:57.903709+00:00 | 1,259 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int numTeams(int[] rating) {\n int n=rating.length;\n\n int nge[]=new int[n];\n int nse[]=new int[n];\n\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n if(rating[i]<rating[j]){\n nge[i]++;\n }\n else nse[i]++;\n }\n }\n int cnt=0;\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n if(rating[i]<rating[j]){\n cnt+=nge[j];\n }\n else cnt+=nse[j];\n }\n }\n return cnt;\n }\n}\n``` | 12 | 0 | ['Array', 'Java'] | 3 |
count-number-of-teams | Python O(N^2) Simple DP Solution | python-on2-simple-dp-solution-by-janos02-7opp | \nclass Solution:\n def numTeams(self, ratings: List[int]) -> int:\n upper_dps = [0 for _ in range(len(ratings))]\n lower_dps = [0 for _ in ran | janos0207 | NORMAL | 2022-04-19T13:17:13.494087+00:00 | 2022-04-19T13:17:13.494119+00:00 | 1,449 | false | ```\nclass Solution:\n def numTeams(self, ratings: List[int]) -> int:\n upper_dps = [0 for _ in range(len(ratings))]\n lower_dps = [0 for _ in range(len(ratings))]\n \n count = 0\n for i in range(len(ratings)):\n for j in range(i):\n if ratings[j] < ratings[i]:\n count += upper_dps[j]\n upper_dps[i] += 1\n else:\n count += lower_dps[j]\n lower_dps[i] += 1\n \n return count\n``` | 12 | 1 | ['Dynamic Programming', 'Python'] | 2 |
count-number-of-teams | ES6 JavaScript O(N^2) beats 98% with explanation | es6-javascript-on2-beats-98-with-explana-zpwn | Every team is consist of 3 members, say Left, Middle and Right. (Left = rating[i], Middle = rating[j], Right = rating[k])\n\nIf the value is in ascending order | space_sailor | NORMAL | 2020-10-05T15:20:51.474956+00:00 | 2020-10-05T15:21:59.371750+00:00 | 840 | false | Every team is consist of 3 members, say **Left**, **Middle** and **Right**. (Left = rating[i], Middle = rating[j], Right = rating[k])\n\nIf the value is in ascending order: **Left** < **Middle** < **Right**\nIf the value is in descending order: **Left** > **Middle** > **Right**\n\nBy checking the posible **Left** member count and **Right** member count, we can then get the total composition count by multiplying them. \n(Note that we need to calculate **asc**ending and **desc**ending count separately.)\n\n```\nconst numTeams = rating => {\n let ans = 0;\n\n // \'i\' is the index of Middle\n for (let i = 1; i < rating.length - 1; i++) {\n let descLeft = 0;\n let descRight = 0;\n\tlet ascLeft = 0;\n\tlet ascRight = 0;\n\n // Check for Left\n for (let j = 0; j < i; j++) {\n if (rating[j] > rating[i]) descLeft++;\n if (rating[j] < rating[i]) ascLeft++;\n }\n\n // Check for Right\n for (let j = i + 1; j < rating.length; j++) {\n if (rating[j] < rating[i]) descRight++;\n if (rating[j] > rating[i]) ascRight++;\n }\n\n ans += descLeft * descRight + ascLeft * ascRight;\n }\n\n return ans;\n};\n``` | 12 | 2 | ['JavaScript'] | 1 |
count-number-of-teams | Counting All The Valid Teams with Simple Brute Force, Easy to Understand Solution! | counting-all-the-valid-teams-with-simple-03w5 | Intuition\nSince the Constraints are in such a way that we can take our chances with a Brute Force Approach, We will go down that route, For any index i if we k | sxnchayyyy | NORMAL | 2024-07-29T09:35:10.989849+00:00 | 2024-07-29T09:35:10.989870+00:00 | 903 | false | # Intuition\nSince the Constraints are in such a way that we can take our chances with a Brute Force Approach, We will go down that route, For any index *i* if we know exactly what sort of numbers are ahead of it and what sort of numbers are behind it we can easily tell how many teams can be formed.\n\n# Approach\nIn this problem We can see that the rating of the teammates should be either striclty increasing or decreasing.\nNow for a team with increasing rating values, for any index $$i$$, The Greater elements that are ahead of the current index and the Smaller elements that are behind the current index will end up making a valid team, so for this type of team we can easily find the elements that are ahead and greater and behind and smaller and simply multiply them to find the number of valid team that follow the given conditions\nSimilarily for the team that is valid with decreasing rating value, for every index $$i$$, We will find the number of greater elements that are behing it and the number the smaller elements that are ahead of it, we can multiply those numbers to find out the valid teams that we can make with that soldier at index $$i$$\nSeperately find the number of valid increasing and decreasing rating teams and return the sum of those team to get the total valid teams.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ We have to traverse pretty much the whole array for every index\n\n- Space complexity:\n$$O(n)$$ We have to store the elements in a linear data structure, I have used a vector\n\n# Code\n```\n#include <bits/stdc++.h>\nusing namespace std;\n#define nline \'\\n\'\n#define sp \' \'\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\nstatic int fastIO = []\n{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n return 0;\n}();\n// Paste the Class here-\nclass Solution\n{\nprivate:\n int increasingsubs(vector<int> &rating, int n)\n {\n vector<int> greaterahead(n);\n vector<int> smallerbehind(n);\n for (int i = 0; i < n; i++)\n {\n int count = 0;\n for (int j = i + 1; j < n; j++)\n {\n if (rating[j] > rating[i])\n count++;\n }\n greaterahead[i] = count;\n }\n for (int i = 0; i < n; i++)\n {\n int count = 0;\n for (int j = i - 1; j >= 0; j--)\n {\n if (rating[j] < rating[i])\n count++;\n }\n smallerbehind[i] = count;\n }\n int increasing = 0;\n for (int i = 0; i < n; i++)\n {\n increasing += greaterahead[i] * smallerbehind[i];\n }\n\n return increasing;\n }\n\n int decreasingsubs(vector<int> &rating, int n)\n {\n vector<int> greaterbehind(n);\n vector<int> smallerahead(n);\n for (int i = 0; i < n; i++)\n {\n int count = 0;\n for (int j = i + 1; j < n; j++)\n {\n if (rating[j] < rating[i])\n count++;\n }\n smallerahead[i] = count;\n }\n for (int i = 0; i < n; i++)\n {\n int count = 0;\n for (int j = i - 1; j >= 0; j--)\n {\n if (rating[j] > rating[i])\n count++;\n }\n greaterbehind[i] = count;\n }\n int decreasing = 0;\n for (int i = 0; i < n; i++)\n {\n decreasing += greaterbehind[i] * smallerahead[i];\n }\n return decreasing;\n }\n\npublic:\n int numTeams(vector<int> &rating)\n {\n int n = rating.size();\n int increasing = increasingsubs(rating, n);\n int decreasing = decreasingsubs(rating, n);\n return increasing + decreasing;\n }\n};\n```\n\n\n# Upvote\n\n | 11 | 0 | ['C++'] | 6 |
count-number-of-teams | SIMPLE AND EASY SOLUTION | simple-and-easy-solution-by-abb333-eg7u | Complexity\n- Time complexity: O(N^3)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# | abb333 | NORMAL | 2024-07-29T03:16:17.708441+00:00 | 2024-07-29T03:16:17.708464+00:00 | 1,471 | false | # Complexity\n- Time complexity: O(N^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n int count = 0;\n\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n for (int k = j + 1; k < n; ++k) {\n if ((rating[i] < rating[j] && rating[j] < rating[k]) ||\n (rating[i] > rating[j] && rating[j] > rating[k])) {\n count++;\n }\n }\n }\n }\n \n return count;\n }\n};\n\n``` | 11 | 2 | ['Array', 'C++'] | 0 |
count-number-of-teams | [C++] Beats 100%, O(N^2) with Explanation | c-beats-100-on2-with-explanation-by-huna-ezwe | Idea :\nWe start a j loop between 1...n-1 to check all valid positions to fix j.\nAt every such position, we check how many elements towards the left are smalle | hunarbatra | NORMAL | 2020-03-29T07:10:04.407020+00:00 | 2020-03-29T07:11:32.268639+00:00 | 943 | false | Idea :\nWe start a j loop between 1...n-1 to check all valid positions to fix j.\nAt every such position, we check how many elements towards the left are smaller than j and how many such elements are greater than j i.e count of i<j & count of i>j\nSimilarly, we check how many elements towards the right of j are greater than j (j<k) and how many such elements are smaller than j (k>j)\nAfter we get this count, the answer for that particular position of j will be :-\n(count of i<j * count of j<k) + (count of i>j * count of j>k)\nThus this comes down to :- answer += (i_smaller * k_larger + i_larger * k_smaller);\nAnd this brings the time complexity down from the brute force O(N^3) to O(N^2) i.e Quadratic runtime.\n\n```\nint numTeams(vector<int>& rating) { //O(N^2)\n if(rating.empty()) return 0;\n int ans = 0;\n for(int j=1; j<rating.size()-1; j++) { //Fixing j\'s position\n int i_smaller=0, i_larger=0, k_smaller=0, k_larger=0;\n for(int i=0; i<j; i++) { //check towards j\'s left\n if(rating[i] < rating[j]) i_smaller++;\n else if(rating[i] > rating[j]) i_larger++;\n }\n for(int k=j+1; k<rating.size(); k++) { //check towards j\'s right\n if(rating[j] < rating[k]) k_larger++;\n else if(rating[j] > rating[k]) k_smaller++;\n }\n ans += i_smaller * k_larger + i_larger * k_smaller;\n }\n return ans;\n }\n```\nTime Complexity : O(N^2)\nSpace Complexity : O(1) | 10 | 0 | ['C', 'C++'] | 6 |
count-number-of-teams | Simple Java solution O(n * n) | simple-java-solution-on-n-by-ashish53v-ep95 | \nclass Solution {\n public int numTeams(int[] rating) {\n int res = 0;\n int[] greater = new int[rating.length];\n int[] smaller = new | ashish53v | NORMAL | 2020-03-29T04:02:06.161037+00:00 | 2020-03-29T04:02:06.161093+00:00 | 1,247 | false | ```\nclass Solution {\n public int numTeams(int[] rating) {\n int res = 0;\n int[] greater = new int[rating.length];\n int[] smaller = new int[rating.length];\n for(int i = 0; i < rating.length - 1; i++){\n int count1 = 0, count2 = 0;\n for(int j = i + 1; j < rating.length; j++){\n if(rating[j] > rating[i]){\n count1++;\n }\n if(rating[j] < rating[i]){\n count2++;\n }\n }\n greater[i] = count1;\n smaller[i] = count2;\n }\n for(int i = 0; i < rating.length - 2; i++){\n for(int j = i + 1; j < rating.length - 1; j++){\n if(rating[j] > rating[i]){\n res += greater[j];\n }\n if(rating[j] < rating[i]){\n res += smaller[j];\n }\n }\n }\n return res;\n }\n}\n``` | 10 | 0 | [] | 1 |
count-number-of-teams | O[n^2] C++ solution, beats 99% | on2-c-solution-beats-99-by-pdx123-2pj5 | Intution is - pick the middle point. Find left side smaller and larger, find right side smaller and larger (in O[N])\n\nTotal teams for this middle point = (lef | pdx123 | NORMAL | 2020-10-15T00:57:13.440502+00:00 | 2020-10-15T00:57:13.440533+00:00 | 516 | false | Intution is - pick the middle point. Find left side smaller and larger, find right side smaller and larger (in O[N])\n\nTotal teams for this middle point = (left_side_smaller * right_side_bigger + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t left_side_bigger * right_side_smaller)\n\n\n\n```class Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int i, j, k;\n int teams = 0;\n \n for (j = 1 ; j < rating.size() - 1 ; j++) {\n int left_side_smaller = 0;\n int left_side_bigger = 0;\n int right_side_smaller = 0;\n int right_side_bigger = 0;\n \n for (i = 0; i < j; i++) {\n if (rating[i] < rating[j]) {\n left_side_smaller++ ; \n } else {\n left_side_bigger++ ;\n }\n }\n \n for (k = j+1 ; k < rating.size(); k++) {\n \n \n if (rating[k] < rating[j]) {\n \n right_side_smaller++;\n } else {\n right_side_bigger++;\n }\n }\n \n teams += (left_side_smaller * right_side_bigger + \n left_side_bigger * right_side_smaller);\n }\n \n \n \n return teams;\n }\n}; | 9 | 0 | [] | 0 |
count-number-of-teams | JavaScript DP Beats 100% with explanation | javascript-dp-beats-100-with-explanation-8cr2 | The basic idea here is that we\'re keeping track of two arrays: one that lists the number of integers after rating[i] that are greater than rating[i], and anoth | ryvol | NORMAL | 2020-03-30T18:50:47.143373+00:00 | 2020-03-30T18:50:47.143419+00:00 | 679 | false | The basic idea here is that we\'re keeping track of two arrays: one that lists the number of integers after rating[i] that are greater than rating[i], and another that lists the number of integers after rating[i] that are less than rating[i]. We do this with nested for loops. \n\nFor the input `[2,5,3,4,1]`, this yields the following arrays:\n\n```\n[ 3, 0, 1, 0, 0 ]\n[ 1, 3, 1, 1, 0 ]\n```\n\nWe then use another nested forloop, where `i` only increases up until the third to last integer in rating. If `rating[j] > rating[i]` then we know we can add greaterThan[j] teams to our total number of teams. The "teams" this represents is effectively (Player i, Player j, Player x where x is a number after j greater than j). \n\nSimilarly, If `rating[j] < rating[i]`, then we can add lessThan[j] number of teams to our result. \n\n**Full Solution:**\n```\n/**\n * @param {number[]} rating\n * @return {number}\n */\nconst numTeams = (rating) => {\n if(rating.length < 3) return 0;\n let result = 0;\n\n let greaterThan = new Array(rating.length).fill(0);\n let lessThan = new Array(rating.length).fill(0);\n\n for(let i = 0; i < rating.length; i++) {\n for(let j = i + 1; j < rating.length; j++) {\n if(rating[j] > rating[i]) {\n ++greaterThan[i];\n } else if(rating[j] < rating[i]) {\n ++lessThan[i];\n }\n }\n }\n \n for(let i = 0; i < rating.length - 2; i++) {\n for(let j = i + 1; j < rating.length; j++) {\n if(rating[j] > rating[i]) {\n result += greaterThan[j];\n } else if(rating[j] < rating[i]) {\n result += lessThan[j];\n }\n }\n }\n\n return result; \n};\n``` | 9 | 0 | [] | 4 |
count-number-of-teams | 3 Java solutions: Brute force / DP / Math | 3-java-solutions-brute-force-dp-math-by-po34j | Method 1: Brute force\n\n Time: O(N^3)\n Space: O(1)\n\n\nclass Solution {\n public int numTeams(int[] rating) {\n int n = rating.length, cnt = 0;\n | motorix | NORMAL | 2020-03-29T04:41:38.152131+00:00 | 2020-05-19T03:53:49.932543+00:00 | 1,100 | false | **Method 1: Brute force**\n\n* Time: ```O(N^3)```\n* Space: ```O(1)```\n\n```\nclass Solution {\n public int numTeams(int[] rating) {\n int n = rating.length, cnt = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < i; j++) {\n if(rating[i] < rating[j]) {\n for(int k = 0; k < j; k++) {\n if(rating[j] < rating[k]) cnt++;\n }\n }\n if(rating[i] > rating[j]) {\n for(int k = 0; k < j; k++) {\n if(rating[j] > rating[k]) cnt++;\n }\n }\n }\n }\n return cnt;\n }\n}\n```\n\n---\n\n\n**Method 2: DP solution**\n\n\n**Idea:**\n\n1. First, we calculate this case ```rating[i] > rating[j] > rating[k]``` given that ```i > j > k```. Then, calculate the case ```rating[i] < rating[j] < rating[k]```.\n2. Define ```dp[i]```: How many items in rating from ```0``` to ```i-1``` are smaller than ```rating[i]```.\n3. For every time we found ```rating[i] > rating[j]```, we accumulate ```dp[j]```. Here, ```dp[j]``` means how many ```rating[k]``` exist from ```0``` to ```j-1```. That is, how many cases satisfy ```rating[i] > rating[j] > rating[k]```.\n\n\n* Time: ```O(N^2)```\n* Space: ```O(N)```\n\n```\nclass Solution {\n public int numTeams(int[] rating) {\n return helper(rating) + helper(reverse(rating));\n }\n private int helper(int[] rating) {\n int n = rating.length, ans = 0;\n int[] dp = new int[n];\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < i; j++) {\n if(rating[i] > rating[j]) {\n dp[i]++;\n ans += dp[j];\n }\n }\n }\n return ans;\n }\n private int[] reverse(int[] rating) {\n int l = 0, r = rating.length-1;\n while(l < r) {\n int tmp = nums[i];\n nums[i] = nums[j];\n nums[j] = tmp;\n l++;\n r--;\n }\n return rating;\n }\n}\n```\n\n---\n\n**Method 3: Mathematic solution**\n\n**Idea:**\n\n1. For a given ```rating[j]```,\n\t1. Find how many items on the left side ```rating[i]``` are smaller than ```rating[j]```.\n\t2. Find how many items on the left side ```rating[i]``` are larger than ```rating[j]```.\n\t3. \tFind how many items on the right side ```rating[k]``` are smaller than ```rating[j]```.\n\t4. \tFind how many items on the right side ```rating[k]``` are larger than ```rating[j]```.\n2. For a given ```rating[j]```, accumulate \n\t1. ```leftsmaller * rightlarger``` which means how many cases are ```rating[i] < rating[j] < rating[k]```, and\n\t2. ```leftlarger * rightsmaller```, which means how many cases are ```rating[i] > rating[j] > rating[k]```.\n\n\n* Time: ```O(N^2)```\n* Space: ```O(1)```\n\n```\nclass Solution {\n public int numTeams(int[] rating) {\n int ans = 0, n = rating.length;\n for(int j = 0; j < n; j++) {\n int leftsmaller = 0, leftlarger = 0, rightsmaller = 0, rightlarger = 0;\n // On the left side of j\n for(int i = 0; i < j; i++) {\n if(rating[i] < rating[j]) leftsmaller++;\n if(rating[i] > rating[j]) leftlarger++;\n }\n // On the right side of j\n for(int k = j+1; k < n; k++) {\n if(rating[k] < rating[j]) rightsmaller++;\n if(rating[k] > rating[j]) rightlarger++;\n }\n ans += leftsmaller * rightlarger + leftlarger * rightsmaller;\n }\n return ans;\n }\n}\n\n``` | 9 | 0 | [] | 2 |
count-number-of-teams | [Java] DP O(N^2) | java-dp-on2-by-peritan-8rzn | asc[i][j]: number of ASC sequence with len i end at rating[j]\ndesc[i][j]: number of DESC sequence with len i end at rating[j]\n\nBase Case\nasc[1][j]= 1, desc[ | peritan | NORMAL | 2020-03-29T04:06:19.219537+00:00 | 2020-03-29T04:21:28.656599+00:00 | 824 | false | `asc[i][j]`: number of ASC sequence with `len i` end at `rating[j]`\n`desc[i][j]`: number of DESC sequence with `len i` end at `rating[j]`\n\n**Base Case**\nasc[1][j]= 1, desc[1][j] = 1 for 0 <= j < n\n\n**Calculate 2 <= i <= 3**\nasc[i][j] = sum(asc[i-1][k]) where 0 <= k < j && rating[k] < rating[r]\ndesc[i][j] = sum(desc[i-1][k]) where 0 <= k < j && rating[k] > rating[r]\n\n\nthe answer will be sum of asc[3][j] + desc[3][j] for 0 <= j < n\ncan do the summing up during i == 3 for speedup\n\n```\nclass Solution {\n public int numTeams(int[] rating) {\n final int n = rating.length;\n int[][] asc = new int[4][n];\n int[][] desc = new int[4][n];\n for (int i = 0; i < n; i++) {\n asc[1][i] = 1;\n desc[1][i] = 1;\n }\n int ret = 0;\n for (int i = 2; i <= 3; i++) {\n for (int r = 1; r < n; r++) {\n for (int l = 0; l < r; l++) {\n if (rating[l] < rating[r])\n asc[i][r] += asc[i-1][l];\n if (rating[l] > rating[r])\n desc[i][r] += desc[i-1][l];\n }\n if (i == 3)\n ret += asc[i][r] + desc[i][r];\n }\n \n }\n return ret;\n }\n}\n``` | 9 | 0 | [] | 1 |
count-number-of-teams | EASIEST JAVA SOLUTION EVER !!! (Recursive + Memoized + Tabulation ) All 3 Approaches !!! | easiest-java-solution-ever-recursive-mem-2640 | Intuition\n\n- This problem is just a variation of LIS(Longest Increasing Subsequence).\n- Here we just have to find the LIS and LDS of the given array.\n- Simi | trinityhunter1 | NORMAL | 2022-12-26T03:05:00.729754+00:00 | 2022-12-26T03:05:00.729788+00:00 | 1,116 | false | # Intuition\n\n- This problem is just a variation of LIS(Longest Increasing Subsequence).\n- Here we just have to find the LIS and LDS of the given array.\n- Similarly, in LIS we find the maximum length of the Increasing SubSequence.\n- Here we simply need to find the total number of Increasing and Decreasing Subsequences with length 3.\n\n# Approach\n**Recursive Approach**\n\n# Code\n```\nclass Solution {\n\n public static int helper2(int[] rating, int ind, int prev, int count){\n\n if(count == 0){\n return 1;\n }\n\n if(ind == rating.length){\n return 0;\n }\n\n int notPick = helper2(rating, ind+1, prev, count);\n\n int pick = 0;\n\n if(prev == -1 || rating[ind]<rating[prev]){\n pick = helper2(rating, ind+1, ind, count-1);\n }\n\n return pick + notPick;\n\n }\n\n public static int helper1(int[] rating, int ind, int prev, int count){\n\n if(count == 0){\n return 1;\n }\n\n if(ind == rating.length){\n return 0;\n }\n\n int notPick = helper1(rating, ind+1, prev, count);\n\n int pick = 0;\n\n if(prev == -1 || rating[ind]>rating[prev]){\n pick = helper1(rating, ind+1, ind, count-1);\n }\n\n return pick + notPick;\n\n }\n\n public int numTeams(int[] rating) {\n \n int ans1 = helper1(rating, 0, -1, 3);\n\n int ans2 = helper2(rating, 0, -1, 3);\n\n return ans1+ans2;\n\n }\n\n}\n```\n\n\n# Approach\n**Recursive + Memoized (Top Down) Approach**\n\n# Code\n```\nclass Solution {\n\n public static int helper2(int[] rating, int ind, int prev, int count){\n\n if(count == 0){\n return 1;\n }\n\n if(ind == rating.length){\n return 0;\n }\n\n if(dp2[ind][prev+1][count]!=null){\n return dp2[ind][prev+1][count];\n }\n\n int notPick = helper2(rating, ind+1, prev, count);\n\n int pick = 0;\n\n if(prev == -1 || rating[ind]<rating[prev]){\n pick = helper2(rating, ind+1, ind, count-1);\n }\n\n return dp2[ind][prev+1][count] = pick + notPick;\n\n }\n\n public static int helper1(int[] rating, int ind, int prev, int count){\n\n if(count == 0){\n return 1;\n }\n\n if(ind == rating.length){\n return 0;\n }\n\n if(dp1[ind][prev+1][count]!=null){\n return dp1[ind][prev+1][count];\n }\n\n int notPick = helper1(rating, ind+1, prev, count);\n\n int pick = 0;\n\n if(prev == -1 || rating[ind]>rating[prev]){\n pick = helper1(rating, ind+1, ind, count-1);\n }\n\n return dp1[ind][prev+1][count] = pick + notPick;\n\n }\n\n public static Integer[][][] dp1;\n\n public static Integer[][][] dp2;\n\n public int numTeams(int[] rating) {\n\n dp1 = new Integer[rating.length][rating.length+1][4];\n \n int ans1 = helper1(rating, 0, -1, 3);\n\n dp2 = new Integer[rating.length][rating.length+1][4];\n\n int ans2 = helper2(rating, 0, -1, 3);\n\n return ans1+ans2;\n\n }\n\n}\n```\n\n# Approach\n**Tabulation (Bottom Up) Approach**\n\n# Code\n```\nclass Solution {\n \n\tpublic int numTeams(int [] rating) {\n\n\t\tint length = rating.length;\n\n\t\tint [] dp = new int[length];\n\n\t\tint count = 0;\n\n\t\tfor (int i=0; i<length; i++) {\n\t\t\tfor (int j=i; j>=0; j--) {\n\t\t\t\tif (rating[i] < rating[j]) {\n\t\t\t\t\tdp[i] += 1;\n\t\t\t\t\tcount += dp[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdp = new int[length];\n\n\t\tfor (int i=0; i<length; i++) {\n\t\t\tfor (int j=i; j>=0; j--) {\n\t\t\t\tif (rating[i] > rating[j]) {\n\t\t\t\t\tdp[i] += 1;\n\t\t\t\t\tcount += dp[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n\n }\n\n}\n```\n | 8 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'Java'] | 3 |
count-number-of-teams | Clean python O(n^2) solution using dictionaries | clean-python-on2-solution-using-dictiona-4dll | \nclass Solution:\n def numTeams(self, arr: List[int]) -> int:\n\t\t# cache to store indices which have a value greater than current index\n memoGreat | ritikbhatia | NORMAL | 2021-01-09T04:17:46.959774+00:00 | 2021-01-09T04:18:08.302451+00:00 | 1,453 | false | ```\nclass Solution:\n def numTeams(self, arr: List[int]) -> int:\n\t\t# cache to store indices which have a value greater than current index\n memoGreater = {}\n \n\t\t# cache to store indices which have a value lesser than current index\n\t\tmemoLesser = {}\n length = len(arr)\n \n\t\tfor i in range(length):\n memoGreater[i] = []\n memoLesser[i] = []\n for j in range(i+1, length):\n if arr[j] > arr[i]:\n memoGreater[i].append(j)\n elif arr[j] < arr[i]:\n memoLesser[i].append(j)\n \n numTeams = 0\n\t\t# add the teams using the conditions specified\n for i in range(length):\n for index in memoGreater[i]:\n numTeams += len(memoGreater[index])\n for index in memoLesser[i]:\n numTeams += len(memoLesser[index])\n \n return numTeams\n``` | 8 | 0 | ['Python', 'Python3'] | 2 |
count-number-of-teams | Java 2 ms DP | java-2-ms-dp-by-avinash3371-m7bp | \n//build up array and down array i.e the number of up and down element for current point \n//add up triplet counts\npublic int numTeams(int[] rating) {\n | avinash3371 | NORMAL | 2020-11-01T20:11:18.857902+00:00 | 2020-11-01T20:11:18.857936+00:00 | 636 | false | ```\n//build up array and down array i.e the number of up and down element for current point \n//add up triplet counts\npublic int numTeams(int[] rating) {\n \n int n = rating.length;\n\n\t\tint[] up = new int[n];\n\t\tint[] down = new int[n];\n\n\t\tint teams = 0;\n\n\t\tfor (int i = n - 1; i >= 0; i--) {\n\t\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\t\tif (rating[i] < rating[j]) {\n\t\t\t\t\tup[i] += 1;\n\t\t\t\t\tteams += up[j];\n\t\t\t\t} else {\n\t\t\t\t\tdown[i] += 1;\n\t\t\t\t\tteams += down[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn teams;\n }\n\t\n\t\n``` | 8 | 0 | [] | 2 |
count-number-of-teams | [Python] Easy to understand O(N^2) Dynamic Programming and O(N^3) | python-easy-to-understand-on2-dynamic-pr-94uq | O(N^2) DP\n\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n if n < 3:\n return 0\n \n | raquelg | NORMAL | 2020-09-15T11:14:04.231315+00:00 | 2020-09-15T11:14:04.231376+00:00 | 1,743 | false | **O(N^2) DP**\n```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n if n < 3:\n return 0\n \n g = [0] * n # <- Greater count\n s = [0] * n # <- Smaller count\n res = 0 # <- number of teams\n \n # For each soldier, we search the next greater and smaller\n for i in range(n - 1):\n for j in range(i + 1, n):\n if rating[j] > rating[i]: \n g[i] += 1\n else:\n s[i] += 1\n \n # Now, we looking for the "last number" . If rating[i] < rating[j] then g[j] are the following possible numbers\n # . rating[i] > rating[j] s[j] \n for i in range(n - 2):\n for j in range(i + 1, n):\n if rating[j] > rating[i]:\n res += g[j]\n else:\n res += s[j]\n \n return res\n```\n\n**O(N^3)**\n```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n mx = max(rating)\n mn = min(rating)\n n = len(rating)\n n1 = n - 1\n \n res = 0\n \n for i in range(n - 2):\n for j in range(i + 1, n1):\n if rating[i] < rating[j] and rating[j] == mx:\n continue\n if rating[i] > rating[j] and rating[j] == mn:\n continue\n \n for k in range(j + 1, n):\n if rating[i] > rating[j] > rating[k] or rating[i] < rating[j] < rating[k]: \n res += 1\n return res\n``` | 8 | 0 | ['Dynamic Programming', 'Python3'] | 5 |
count-number-of-teams | C++ || Comments Code || 4ms || 99.2 % Faster || Comments | c-comments-code-4ms-992-faster-comments-zr8eq | Credits : Anonymous_Kumar\nRemember we have to do for ij>k\n\nclass Solution {\npublic:\n int numTeams(vector<int>& arr) {\n int n = arr.size();\n | tsm_en_curious | NORMAL | 2020-09-05T16:46:43.565660+00:00 | 2020-09-05T16:46:43.565722+00:00 | 640 | false | Credits : Anonymous_Kumar\nRemember we have to do for i<j<k ; i>j>k\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& arr) {\n int n = arr.size();\n int result = 0;\n for(int i = 1 ; i < n-1 ; i++){\n int leftSmall = 0, leftLarge = 0;\n int rightSmall = 0, rightLarge = 0;\n //left part\n for(int j = 0 ; j < i ; j++){\n if(arr[j] < arr[i]){\n leftSmall++;\n }\n if(arr[j] > arr[i]){\n leftLarge++;\n }\n }\n //right part\n for(int j = i+1 ; j < n ; j++){\n if(arr[j] < arr[i]){\n rightSmall++;\n }\n if(arr[j] > arr[i]){\n rightLarge++;\n }\n }\n \n result += leftSmall * rightLarge + leftLarge * rightSmall;\n //Part 1 of above equation for no.of pairs possible when i<j<k with mid element as arr[i]\n //Part 2 of above equation for no.of pairs possible when i>j>k with mid element as arr[i]\n }\n return result;\n }\n};\n``` | 8 | 0 | ['C'] | 1 |
count-number-of-teams | C++: Simple backtracking | c-simple-backtracking-by-haldiya-i2ip | \nint count;\n \n void backtrack(vector<int> & rating, int start, int end, vector<int> & arr){\n if( (arr.size() == 3 && arr[0] < arr[1] && arr[1] | haldiya | NORMAL | 2020-03-30T07:47:25.839152+00:00 | 2020-03-30T07:47:25.839187+00:00 | 592 | false | ```\nint count;\n \n void backtrack(vector<int> & rating, int start, int end, vector<int> & arr){\n if( (arr.size() == 3 && arr[0] < arr[1] && arr[1] < arr[2]) || (arr.size() == 3 && arr[0] > arr[1] && arr[1] > arr[2])){\n count++;\n return;\n }\n if(arr.size() < 3)\n for (int i=start;i<=end;i++){\n arr.push_back(rating[i]);\n backtrack(rating, i+1, end, arr);\n arr.pop_back();\n\n }\n }\n \n int numTeams(vector<int>& rating) {\n count = 0;\n vector<int> arr;\n backtrack(rating, 0, rating.size()-1, arr);\n return count;\n }\n``` | 8 | 0 | [] | 2 |
count-number-of-teams | python bisect and insort | python-bisect-and-insort-by-cubicon-mqmt | \ndef numTeams(self, r: List[int]) -> int:\n def nteams(r):\n a, res = [], 0\n left, right = [0] * len(r), [0] * len(r) \n | Cubicon | NORMAL | 2020-03-29T04:02:21.502355+00:00 | 2020-03-29T04:02:21.502410+00:00 | 662 | false | ```\ndef numTeams(self, r: List[int]) -> int:\n def nteams(r):\n a, res = [], 0\n left, right = [0] * len(r), [0] * len(r) \n for i in range(len(r)):\n left[i] = bisect_left(a, r[i]) \n bisect.insort(a, r[i])\n a = []\n for i in range(len(r)-1, -1, -1):\n right[i] = len(a) - bisect_right(a, r[i])\n bisect.insort(a, r[i])\n for i in range(len(r)):\n if left[i] != 0 and right[i] != 0:\n res += (left[i] * right[i])\n return res\n return nteams(r) + nteams(r[::-1]) \n``` | 8 | 2 | [] | 2 |
count-number-of-teams | C++ || Greedy + Intuition Based | c-greedy-intuition-based-by-batman14-eflp | Intuition\n Describe your first thoughts on how to solve this problem. \nGREEDYYYYYY !!!!\n\n# Approach\n Describe your approach to solving the problem. \n\nFor | batman14 | NORMAL | 2023-04-07T07:43:41.681483+00:00 | 2023-04-07T07:43:41.681512+00:00 | 1,380 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGREEDYYYYYY !!!!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nFor an index to form a team : \n one element smaller in left + curr element + one element larger in right\n OR\n one element larger in left + curr element + one element smaller in right\n\n\nAnd, we have to find the number of smaller & larger elememts in Left of a certain element AND the number of smaller & larger elememts in Right of a certain element.\n\n\n\nKeeping the above in consideration , we can say the number of teams we can form using a current index will be =>\n\ncurr_idx_teams = (left_smaller*right_larger) + (left_larger*right_smaller)\n\n\nDo this over each element and thus obtaining the number of teams possible with each index and add them to get the total.\n\n\n\n\n\n\n# Complexity\n- Time complexity : O(N*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n int total_teams = 0;\n\n for(int idx=0; idx<n; idx++) {\n\n int left_smaller=0, left_larger=0, right_smaller=0, right_larger=0;\n\n for(int l=idx-1; l>=0; l--) {\n if(rating[l]<rating[idx]) {\n left_smaller++;\n }\n else {\n left_larger++;\n }\n }\n\n for(int r=idx+1; r<n; r++) {\n if(rating[r]<rating[idx]) {\n right_smaller++;\n }\n else {\n right_larger++;\n }\n }\n\n\n int curr_idx_teams = (left_smaller*right_larger) + (left_larger*right_smaller);\n\n total_teams += curr_idx_teams;\n }\n\n return total_teams;\n }\n};\n``` | 7 | 0 | ['Dynamic Programming', 'Greedy', 'C++'] | 2 |
count-number-of-teams | Easy understanding using recursion +memomization | easy-understanding-using-recursion-memom-7kcj | \nclass Solution {\npublic:\n int dp1[1002][1002][4];\n int numTeams(vector<int>& arr) {\n \n memset(dp1,-1,sizeof(dp1));\n \n | akshat0610 | NORMAL | 2022-08-22T07:18:00.417125+00:00 | 2022-08-22T07:22:23.493507+00:00 | 1,842 | false | ```\nclass Solution {\npublic:\n int dp1[1002][1002][4];\n int numTeams(vector<int>& arr) {\n \n memset(dp1,-1,sizeof(dp1));\n \n \n int idx=0;\n int prv=-1;\n int k=3;\n int count1=fun1(arr,idx,prv,k);\n \n \n memset(dp1,-1,sizeof(dp1));\n idx=0;\n prv=-1;\n k=3;\n int count2=fun2(arr,idx,prv,k);\n \n return count1+count2;\n }\n int fun1(vector<int>&arr,int idx,int prv,int k)\n {\n //base\n \n if(k==0)\n return 1; \n \n if(idx>=arr.size() and k>0)\n return 0;\n if(idx>=arr.size() and k==0)\n return 1;\n \n if(dp1[idx][prv+1][k]!=-1)\n {\n return dp1[idx][prv+1][k];\n }\n \n int choise1=0;\n int choise2=0;\n \n if(prv==-1 or arr[prv]<arr[idx])\n choise1=fun1(arr,idx+1,idx,k-1);\n \n choise2=fun1(arr,idx+1,prv,k);\n \n return dp1[idx][prv+1][k] =choise1+choise2;\n }\n int fun2(vector<int>&arr,int idx,int prv,int k)\n {\n \n if(k==0)\n return 1;\n \n if(idx>=arr.size() and k>0)\n return 0;\n \n if(idx>=arr.size() and k==0)\n return 1;\n \n if(dp1[idx][prv+1][k]!=-1)\n {\n return dp1[idx][prv+1][k];\n }\n \n int choise1=0;\n int choise2=0;\n \n if(prv==-1 or arr[prv]>arr[idx])\n choise1=fun2(arr,idx+1,idx,k-1);\n \n choise2=fun2(arr,idx+1,prv,k);\n \n return dp1[idx][prv+1][k] =choise1+choise2;\n }\n};``\n``` | 7 | 0 | ['Dynamic Programming', 'Memoization', 'C', 'C++'] | 3 |
count-number-of-teams | Python | O(n^2) | Slow but very easy to understand | Explanation | python-on2-slow-but-very-easy-to-underst-78pc | dp[i] is a 3-tuple which indicates the number of teams of size 1, 2, 3 respectively ending with index i\n So, dp is n * 3 matrix. Initialize dp[i] to be [1, 0, | detective_dp | NORMAL | 2021-09-15T18:12:58.906183+00:00 | 2021-09-15T18:12:58.906248+00:00 | 1,190 | false | * dp[i] is a 3-tuple which indicates the number of teams of size 1, 2, 3 respectively ending with index i\n* So, dp is n * 3 matrix. Initialize dp[i] to be [1, 0, 0] because there is only one team with size 1 ending with index i (which is just the team with only index i)\n* Now, for each index i, loop through all indices j from 0 to i - 1 and compare each element to rating[i]. If an element is smaller than rating[i] then that means we can form a team of size 3 with all the teams of size 2 ending with j and we can form a team of size 2 with all teams of size 1 ending with j.\n* The reason we are interested in storing teams of size 1, 2 is because we want to carry the partial solution forward so that we can avoid an extra for loop.\n* Now just add all the teams of size 3 and perform the same nested loops but this time in comparison check for elements larger than rating[i].\n* Let me know in the comments if you have any questions.\n```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n \n dp = [[1, 0, 0] for i in range(len(rating))]\n \n for i in range(1, len(rating)):\n for j in range(i):\n if rating[i] > rating[j]:\n dp[i][1] += dp[j][0]\n dp[i][2] += dp[j][1]\n \n a = sum(dp[i][2] for i in range(len(dp)))\n #print(a)\n\n dp = [[1, 0, 0] for i in range(len(rating))]\n \n for i in range(1, len(rating)):\n for j in range(i):\n if rating[i] < rating[j]:\n dp[i][1] += dp[j][0]\n dp[i][2] += dp[j][1]\n \n b = sum(dp[i][2] for i in range(len(dp)))\n \n return a + b | 7 | 0 | ['Dynamic Programming', 'Python', 'Python3'] | 0 |
count-number-of-teams | C++ | DP Memoization | Simple & Easy Code | c-dp-memoization-simple-easy-code-by-ash-df07 | \nclass Solution {\npublic:\n int dpi[1001][4], dpd[1001][4]; \n\tint numTeams(vector<int>& rating) {\n int n = rating.size();\n int res = 0 | ash_gt7 | NORMAL | 2021-08-23T15:24:03.033790+00:00 | 2021-08-23T15:36:31.304874+00:00 | 1,273 | false | ```\nclass Solution {\npublic:\n int dpi[1001][4], dpd[1001][4]; \n\tint numTeams(vector<int>& rating) {\n int n = rating.size();\n int res = 0;\n \n memset(dpi, -1, sizeof(dpi)); // to memoize increasing sequence\n memset(dpd, -1, sizeof(dpd)); // to memoize decreasing sequence\n \n for(int i=0; i<n; i++){\n res += countInc(rating, i, 1, n) + countDec(rating, i, 1, n); \n }\n return res;\n }\n\t\n // countInc -> counting the the number of Increasing sequence \n int countInc(vector<int> &rating, int i, int solCnt, int n){\n if(dpi[i][solCnt] != -1) return dpi[i][solCnt];\n if(solCnt == 3) return 1;\n \n int cnt = 0;\n for(int k=i+1; k<n; k++){\n if(rating[k] > rating[i])\n cnt += countInc(rating, k, solCnt+1, n);\n }\n return dpi[i][solCnt] = cnt;\n }\n \n\t// countDec -> counting the the number of decreasing sequence \n int countDec(vector<int> &rating, int i, int solCnt, int n){\n if(dpd[i][solCnt] != -1) return dpd[i][solCnt];\n if(solCnt == 3) return 1;\n \n int cnt = 0;\n for(int k=i+1; k<n; k++){\n if(rating[k] < rating[i])\n cnt += countDec(rating, k, solCnt+1, n);\n }\n return dpd[i][solCnt] = cnt;\n }\n};\n``` | 7 | 0 | ['Dynamic Programming', 'Memoization', 'C'] | 2 |
count-number-of-teams | Easy Python O(nlogn) using SortedList | easy-python-onlogn-using-sortedlist-by-b-7eh8 | Look at each soldier, and consider how many teams can be made using them as the middle member. That can be calculated as follows:\n\n(smaller soldiers to left) | btwvcd | NORMAL | 2020-04-26T07:39:54.689626+00:00 | 2020-04-26T07:39:54.689667+00:00 | 591 | false | Look at each soldier, and consider how many teams can be made using them as the middle member. That can be calculated as follows:\n\n(smaller soldiers to left) * (larger soldiers to right) + (larger soldiers to left) * (smaller soldiers to right)\n\nTo accomplish this, we use a SortedList and do an initial pass to find how many smaller and larger soldiers exist before each soldier, and then another pass to find how many smaller and larger soldiers exist after each of them.\n\n```\nfrom sortedcontainers import SortedList\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n before = SortedList()\n before_smaller = [0] * len(rating)\n before_larger = [0] * len(rating)\n\n for i, soldier in enumerate(rating):\n before.add(soldier)\n index = before.index(soldier)\n before_smaller[i] = index\n before_larger[i] = len(before) - index - 1\n \n total = 0\n after = SortedList()\n\n for i in range(len(rating) - 1, -1, -1):\n soldier = rating[i]\n after.add(soldier)\n index = after.index(soldier)\n total += before_smaller[i] * (len(after) - index - 1)\n total += before_larger[i] * index\n \n return total\n``` | 7 | 0 | [] | 0 |
count-number-of-teams | Java beats 100%, 1ms | java-beats-100-1ms-by-aydogdy-oyoo | Time Complexity O(n^2)\nSpace Complecity O(1)\n\n\npublic int numTeams(int[] rating) {\n\tint n = rating.length;\n int ans = 0;\n \n for(int i=0; i<n; | aydogdy | NORMAL | 2020-04-18T02:40:54.641026+00:00 | 2020-04-18T02:41:34.512384+00:00 | 1,860 | false | Time Complexity O(n^2)\nSpace Complecity O(1)\n\n```\npublic int numTeams(int[] rating) {\n\tint n = rating.length;\n int ans = 0;\n \n for(int i=0; i<n; i++) {\n int l = 0;\n int r = 0;\n \n for(int j=0; j<i; j++) {\n if (rating[j] < rating[i]) l++;\n }\n \n for(int k=i+1; k<n; k++) {\n if (rating[i] < rating[k]) r++;\n } \n\t\t\n ans += (l*r) + (i-l)*(n - i - r - 1);\n }\n\n return ans;\n }\n``` | 7 | 1 | ['Java'] | 2 |
count-number-of-teams | Python | Brute Force | python-brute-force-by-khosiyat-08y5 | see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n count | Khosiyat | NORMAL | 2024-07-29T10:10:56.694919+00:00 | 2024-07-29T10:10:56.694942+00:00 | 516 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/count-number-of-teams/submissions/1337131003/?envType=daily-question&envId=2024-07-29)\n\n# Code\n```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n count = 0\n \n for j in range(n):\n left_less = left_greater = right_less = right_greater = 0\n \n for i in range(j):\n if rating[i] < rating[j]:\n left_less += 1\n elif rating[i] > rating[j]:\n left_greater += 1\n \n for k in range(j + 1, n):\n if rating[k] < rating[j]:\n right_less += 1\n elif rating[k] > rating[j]:\n right_greater += 1\n \n count += left_less * right_greater + left_greater * right_less\n \n return count\n \n```\n\n# Steps\n\n1. **Initialize Counters**: For each soldier `j`, maintain two counts:\n - `left_less[j]`: Number of soldiers to the left of `j` with a rating less than `rating[j]`.\n - `left_greater[j]`: Number of soldiers to the left of `j` with a rating greater than `rating[j]`.\n - `right_less[j]`: Number of soldiers to the right of `j` with a rating less than `rating[j]`.\n - `right_greater[j]`: Number of soldiers to the right of `j` with a rating greater than `rating[j]`.\n\n2. **Count Valid Teams**: For each soldier `j`, the number of valid teams where `rating[j]` is the middle soldier can be found by:\n - Teams forming increasing sequences: `left_less[j] * right_greater[j]`.\n - Teams forming decreasing sequences: `left_greater[j] * right_less[j]`.\n\n3. **Sum Up**: Sum all valid teams.\n\n# Explanation of the Code\n\n- **Initialization**: We initialize `n` as the length of the `rating` list and `count` to keep track of valid teams.\n- **Two Nested Loops**: The outer loop iterates through each soldier `j`, and the two inner loops count soldiers to the left and right of `j` that are less or greater in rating.\n- **Counting Valid Teams**: For each `j`, we calculate the number of valid teams where `j` is the middle soldier using the counts from the inner loops.\n- **Sum Up**: The total count of valid teams is returned at the end.\n\n\n | 6 | 0 | ['Python3'] | 0 |
count-number-of-teams | O(N3), O(N2) || All Solutions Explainedโญ๐ | on3-on2-all-solutions-explained-by-_rish-qibm | Counting Number of Valid Teams\n\n## Intuition\nThe problem is to count the number of valid teams of 3 soldiers based on their ratings. A team is valid if it is | _Rishabh_96 | NORMAL | 2024-07-29T07:00:28.347194+00:00 | 2024-07-29T07:00:28.347237+00:00 | 621 | false | # Counting Number of Valid Teams\n\n## Intuition\nThe problem is to count the number of valid teams of 3 soldiers based on their ratings. A team is valid if it is either strictly increasing or strictly decreasing in terms of ratings. \n\n### Approach 1: Triple Nested Loops\nThe most straightforward way is to use three nested loops to iterate through all possible triplets and check if they form a valid team.\n\n### Approach 2: Optimized Counting\nA more efficient way is to count for each soldier how many soldiers to the left are smaller/greater and how many soldiers to the right are smaller/greater. This allows us to calculate the number of valid teams in a single pass for each soldier.\n\n## Approach\n### Triple Nested Loops Approach\n1. Use three nested loops to iterate through all possible triplets `(i, j, k)` where `i < j < k`.\n2. For each triplet, check if it forms a strictly increasing or strictly decreasing sequence.\n3. Count the number of valid triplets.\n\n### Optimized Counting Approach\n1. For each soldier `i`, count how many soldiers to the left are smaller (`leftsmaller`) and greater (`leftgreater`) than `rating[i]`.\n2. Similarly, count how many soldiers to the right are smaller (`rightsmaller`) and greater (`rightgreater`) than `rating[i]`.\n3. For each `i`, the number of valid teams where `i` is the middle soldier is given by `leftsmaller * rightgreater + leftgreater * rightsmaller`.\n\n## Complexity\n### Triple Nested Loops Approach\n- **Time complexity**: \\(O(n^3)\\)\n- **Space complexity**: \\(O(1)\\), not counting the input size\n\n### Optimized Counting Approach\n- **Time complexity**: \\(O(n^2)\\)\n- **Space complexity**: \\(O(1)\\), not counting the input size\n\n## Code\n### Triple Nested Loops Approach\n```cpp\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n int count = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n for (int k = j + 1; k < n; k++) {\n if ((rating[i] < rating[j] && rating[j] < rating[k]) || \n (rating[i] > rating[j] && rating[j] > rating[k])) {\n count++;\n }\n }\n }\n }\n\n return count;\n }\n};\n\n```\n### Optimized Counting Approach\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n \n int n = rating.size();\n int count = 0;\n\n for(int i=0; i<n; i++){\n\n int leftsmaller = 0, leftgreater = 0;\n int rightsmaller = 0, rightgreater = 0;\n\n for(int j=0; j<i ; j++){\n if(rating[j] > rating[i]){\n leftgreater++;\n }\n if(rating[j] < rating[i]){\n leftsmaller++;\n }\n }\n\n for(int j=i+1; j<n ; j++){\n if(rating[j] > rating[i]){\n rightgreater++;\n }\n if(rating[j] < rating[i]){\n rightsmaller++;\n }\n }\n\n count += leftsmaller*rightgreater + leftgreater*rightsmaller;\n }\n\n return count;\n }\n};\n``` | 6 | 0 | ['Array', 'Dynamic Programming', 'Binary Indexed Tree', 'C++'] | 1 |
count-number-of-teams | A stupid Python solution | a-stupid-python-solution-by-jingkailin-23vy | \nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n from itertools import combinations\n \n comb = combinations(rating, | jingkailin | NORMAL | 2021-11-24T03:20:55.328229+00:00 | 2021-11-24T17:30:49.825679+00:00 | 588 | false | ```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n from itertools import combinations\n \n comb = combinations(rating, 3)\n count = 0\n \n for i in comb:\n if ((i[0]>i[1] and i[1]>i[2]) or\n (i[0]<i[1] and i[1]<i[2])):\n \n count+=1\n return count\n```\n\n\n | 6 | 0 | ['Python'] | 3 |
count-number-of-teams | Easy to understand DP solution || Java | easy-to-understand-dp-solution-java-by-s-6xyu | \nclass Solution {\n public int numTeams(int[] rating) {\n int len = rating.length;\n\n\t\tint[] up = new int[len]; \n\t\tint[] down = new int[len];\ | souravpal4 | NORMAL | 2021-11-23T18:09:42.577760+00:00 | 2021-11-23T18:10:02.479473+00:00 | 1,856 | false | ```\nclass Solution {\n public int numTeams(int[] rating) {\n int len = rating.length;\n\n\t\tint[] up = new int[len]; \n\t\tint[] down = new int[len];\n\n\t\tint count = 0;\n \n // first <r[i] <r[j] <r[k] order\n \n for(int i = 0; i < len; i++){\n for(int j = i; j >= 0; j--){\n if(rating[i] > rating[j]){\n up[i]++;\n count = count + up[j];\n }\n }\n }\n \n // second >r[i] >r[j] >r[k] order\n\t\t for(int i = 0; i < len; i++){\n for(int j = i; j >= 0; j--){\n\t\t\t\tif (rating[i] < rating[j]) {\n\t\t\t\t\tdown[i] += 1;\n\t\t\t\t\tcount += down[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n }\n}\n``` | 6 | 0 | ['Dynamic Programming', 'Java'] | 4 |
count-number-of-teams | Python O(n^2) faster than 92.6% | python-on2-faster-than-926-by-thedeadcod-dfn3 | The solution is very intuitive, but feel free to aks questions if something is unclear.\n```\n increasing = [0] * len(rating)\n decreasing = [0] * | thedeadcode957 | NORMAL | 2021-08-18T12:33:04.055112+00:00 | 2021-08-18T12:33:04.055145+00:00 | 319 | false | The solution is very intuitive, but feel free to aks questions if something is unclear.\n```\n increasing = [0] * len(rating)\n decreasing = [0] * len(rating)\n teams = 0\n \n for i in range(1,len(rating)):\n for j in range(i):\n \n if rating[i] > rating[j]:\n increasing[i] += 1 \n teams+= increasing[j]\n else:\n decreasing[i] += 1\n teams+= decreasing[j]\n return teams\n\t\t | 6 | 0 | [] | 1 |
count-number-of-teams | [Python] From DP O(N^2) >88%, to BIT O(NlogN) > 98%, and thought about 100% | python-from-dp-on2-88-to-bit-onlogn-98-a-o8cf | Preface\n\nThis post is a summary about my trip exploring this problem. The question can be solved naively in O(N^3). By a simple "DP" , it can be solved in O(N | jimmywzm | NORMAL | 2021-06-21T04:47:22.973765+00:00 | 2021-06-21T04:59:54.168141+00:00 | 329 | false | **Preface**\n\nThis post is a summary about my trip exploring this problem. The question can be solved naively in O(N^3). By a simple "DP" , it can be solved in O(N^2). I will choose the DP version as the baseline, and show improvements over it. For people not familiar with DP, please check <u>[post #1](https://leetcode.com/problems/count-number-of-teams/discuss/554918/Python-Easy-O(N2)-DP-solution)</u> for the intuition of "DP" solution.\n\n**Abstract Pickup**\n\nThe DP-like O(N^2) solution should be fine for simple interviews. For advanced ones, one should either be familiar with the implementation of BIT, or use the `bisect.insort` cleverly.\n\nTo scale, `SortedList` may be a competitive solution for single server, while SQL window operations in O(N^2) is more practical for distributed situation.\n\n\n**Runtime and Menory table**\n\n<img src="https://assets.leetcode.com/users/images/a96191af-4b56-46a3-80e6-50a0cb3a9f51_1624235989.3516107.png" style="width:600px;height:250px">\n\n**Start From "DP"**\n\nThe basic idea of DP is to keep memo about number of rating smaller or larger than current one. Then we can take advantage of the `lg` and `sm` memo to count the number of valid tuple.\n```\n# My DP #\ndef numTeams(self, rating: List[int]) -> int:\n l = len(rating)-1\n lg,sm,res = [0]*l,[0]*l,0\n for i in range(1,l):\n v = rating[i]\n for j in range(i):\n if v<rating[j]:\n lg[i] += 1\n res += lg[j]\n else:\n sm[i] += 1\n res += sm[j]\n v = rating[-1]\n return res + sum(lg[j] if v<rating[j] else sm[j] for j in range(l))\n```\nWe can easliy found that `lg` and `sm` is redundent. To improve, just remove `sm` and replace the `sm[j]` parts with `(j - lg[j])`. <u>*(DP-v2)*</u>\n\n**Change the Entry Point**\n\nFor a tuple` (i, j, k)`, the DP above trys to iterate first on `k`, look up each `j` before it, then add up either `sm[j]` or `lg[j]` based on the relationship between `rating[k]` and `rating[j]`. If we change the entry point and first iterate on `j`, there is another vaild O(N^2) solution, where we can check valid `i` and `k` for each `j` within O(N). \n\nThis idea is written in <u>[post #2](https://leetcode.com/problems/count-number-of-teams/discuss/565479/python-greater97.98-simple-logic-and-very-detailed-explanation)</u>. Although runtime in this title is outdated and it is slower than the DP above, It is easy to implement and instructive for the O(NlogN) solution.\n\n**Binary Index Tree(BIT)**\n\nIn the section above, we spent O(N) to count valid `i` and `k` for each `j`. What if we can narrow it down to O(logN)? <u> [post #3](https://leetcode.com/problems/count-number-of-teams/discuss/554907/Java-Detailed-Explanation-TreeSet-greater-BIT-(Fenwick-Tree)-O(NlogN)) </u> came up with a clever idea to utlize <u>[BIT](https://en.wikipedia.org/wiki/Fenwick_tree)</u> to calculate valid `i` and `k`. \n\nBIT is a space-efficient structure, which can update element in array and calculate prefix sum in O(logN). In this question, we can take advantage of the uniqueness of the `rating` values and use it as indexs. The BIT here can be used as a counter which can show the amount of smaller or larger numbers in O(logN).\n\nMy simplified version of BIT is followings. Only limitted function is needed for this question.\n```\ndef lastbit(i): return i & -i\ndef parent(i): return i & (i - 1) # parent(i) = i - lastbit(i)\ndef nextpow(i): return i + lastbit(i) \n\nclass BIT:\n def __init__(self,li):\n self.li = li\n\n def adjust(self,i,dv):\n l = len(self.li)\n while i<l:\n self.li[i] += dv\n i = nextpow(i)\n\n def prefixsum(self,i):\n su = 0\n while i > 0:\n su += self.li[i]\n i = parent(i)\n return su\n```\n\nFollowing the post I mentioned, I rewite and accelerate the solution with some math tricks.\n```\n# MY BIT #\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n M,l = max(rating)+1,len(rating)-1\n lt,rt = BIT([0]*M),BIT([0]*M)\n for r in rating: rt.adjust(r,1)\n \n res = 0\n for i,r in enumerate(rating):\n rt.adjust(r,-1)\n p1,p2 = lt.prefixsum(r-1),rt.prefixsum(r-1)\n res += p1*(l-i-p2) + (i-p1)*p2\n lt.adjust(r,1)\n \n return res\n```\nWith futher math inside, the loop part can be revised as this:\n```\n# BIT - v2 #\nfor i,r in enumerate(rating):\n\tp1,p2 = lt.prefixsum(r-1),rt.prefixsum(r-1)\n\tres += p1*(l-p2) + (i-p1)*(p2-p1*2)\n\tlt.adjust(r,1)\n```\n\n**Stain, and Dual Problem**\n\nLet `N=len(rating)` and `M=max(rating)`, the solution above is actually O(NlogM) in time and O(M) in space. The constraint here gives `N<=1000 and M<=100_000`, which makes it a small problem. But if `M` is much larger than `N`, the waste of time and space will be significant. \n\nTo solve this problem and accelerate it to real O(NlogN), we can look at the dual question. The original question is to find `rating[i]<rating[j]<rating[k]`(or reverse) while `i<j<k`. the later condition is guaranteed by the order of `rating` array, so we only need to check the former condition.\n\nNow we can obtain an index array `index` by sorting `rating`, where `rating[index[i1]]<rating[index[i2]]` if `i1<i2`. In another word, `rating[index[i1]]<rating[index[i2]]<rating[index[i3]]` is guaranteed by order of array `index`. The origional question is equavalent to a duel question to check whether `index[i]<index[i2]<index[i3]`(or reverse) in`index` when `i1<i2<i3`.\n\n**BIT Duel Question**\n\nFor the duel problem, the constiant will become `1<= index[i] <=N` (1- indexed). Hence, the time and space complexity are exact O(NlogN) and O(N). The corresponding reversion is here:\n```\n# BIT (duel) #\ndef numTeams(self, rating: List[int]) -> int:\n\tl = len(rating) + 1\n\tindex = sorted(range(1,l), key = lambda i: rating[i-1])\n\tlt,rt = BIT([0]*l),BIT([0]*l)\n\tfor r in index: rt.adjust(r,1)\n\n\tres = 0\n\tl -= 2\n\tfor i,r in enumerate(index):\n\t\tp1,p2 = lt.prefixsum(r-1),rt.prefixsum(r-1)\n\t\tres += p1*(l-p2) + (i-p1)*(p2-p1*2)\n\t\tlt.adjust(r,1)\n\n\treturn res\n```\nAnother advantage of switching to duel problem is that `rt` can be eliminated. Since the values of `index` array are distinct and are exact `1 to N`. The number of index smaller or larger than specific index is really obvious. Hence the final version I have is here:\n```\n# BIT (duel) - v2 #\ndef numTeams(self, rating: List[int]) -> int:\n\tl = len(rating) + 1\n\tindex = sorted(range(1,l), key = lambda i: rating[i-1])\n\tlt = BIT([0]*l)\n\n\tres = 0\n\tl -= 2\n\tfor i,r in enumerate(index):\n\t\tp1,p2 = lt.prefixsum(r-1),r-1\n\t\tres += p1*(l-p2) + (i-p1)*(p2-p1*2)\n\t\tlt.adjust(r,1)\n\n\treturn res\n```\n\n**Check Solutions above 99%**\n\nAfter obtained my final solution, I find that there are still 2% to overcome. So I check the top solutions and find the reason. In brief, O(NlogN) is the best complexity theoritcally, but the constant factor matters here as the N is not large enough.\n\nThe top solution use a clever version of DP with `bisect.insort`. In theory, each insort cost O(N) and in all O(N^2). But it is a little faster since N is small and `insort` is a fully optimized python native operation.\n\n**Scale**\n\nThis reason above is common and not interesting at all. The real interesting part is " `from sortedcontainers import SortedList` " used by one of these solutions, which is useful for scaling. \n\nAfter check the <u> [official website](http://www.grantjenks.com/docs/sortedcontainers/#testimonials) </u> of sortedcontainers, I find that `SortedList` could be a competetive solution for large data handleable by a single server. `SortedList` is an hierarchical list implemented by pure python. It is designed to solve the bad performance of normal `insort` with elements over several thousands. With great design of structure, advantage of locality and optimization on low level, it overperforms other theoritical O(NlogN) structures like AVL-tree, RB-tree, and Skip-list a lot on scale of several billion or trillion, which is almost enough for common use case.\n\nIf the data scale needs to be distributed to store, the choice may be different. DP O(N^2) solution can be easily implemented by `window`, `index`, and `count` in SQL, and further run on Spark over nearly any amount of data. On the contrary, O(NlogN) or `SortedList` solution require frequent adjustments over elements in order, which may not very suit for distributed situation.\n | 6 | 0 | ['Dynamic Programming', 'Binary Indexed Tree'] | 2 |
count-number-of-teams | Clean Python | clean-python-by-dev-josh-fkmm | The idea is the outer-loop is always going to be the middle element. a, b, searches left of the middle, c and d searches the right of the middle. \n\nresult += | dev-josh | NORMAL | 2021-04-17T17:32:42.987450+00:00 | 2021-04-17T17:32:42.987494+00:00 | 1,103 | false | The idea is the outer-loop is *always* going to be the middle element. `a`, `b`, searches *left* of the middle, `c` and `d` searches the *right* of the middle. \n\n`result += a*d + b*c` is just some math. I\'m pretty terrible at math.\n\nOriginal solution: @rmoskalenko\n\n```python\ndef numTeams(rating):\n\n result = 0\n\n for idx, middle in enumerate(rating):\n a = sum(left < middle for jdx, left in enumerate(rating[:idx]))\n b = sum(left > middle for jdx, left in enumerate(rating[:idx])) \n c = sum(right < middle for jdx, right in enumerate(rating[idx+1:]))\n d = sum(middle < right for jdx, right in enumerate(rating[idx+1:]))\n result += a*d + b*c\n\n return result\n``` | 6 | 1 | ['Python', 'Python3'] | 2 |
count-number-of-teams | [C++] O(N^2) Solution | Easy Combinatorics | c-on2-solution-easy-combinatorics-by-vec-rtlq | \nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int ans = 0;\n for(int i=1;i<rating.size()-1;++i){\n int l=0,r=0 | vector_long_long | NORMAL | 2021-01-30T23:17:08.696724+00:00 | 2021-01-30T23:17:08.696774+00:00 | 657 | false | ```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int ans = 0;\n for(int i=1;i<rating.size()-1;++i){\n int l=0,r=0;\n for(int j=0;j<i;++j)\n if(rating[j]<rating[i]) l++;\n for(int j=i+1;j<rating.size();++j)\n if(rating[j]>rating[i]) r++;\n ans += l*r+(i-l)*(rating.size()-i-r-1);\n }\n return ans;\n }\n};\n``` | 6 | 1 | ['C', 'C++'] | 2 |
count-number-of-teams | Recursion & O(N^2) Solution | recursion-on2-solution-by-hemantsingh_he-yf4h | \nApproach 1 : Recursion (Include/Exclude Fashion)\n\nTLE Solution\n\nclass Solution {\npublic:\n int count;\n\t\n bool criteria_fulfilled(const vector<i | hemantsingh_here | NORMAL | 2024-07-29T20:40:14.639040+00:00 | 2024-07-29T20:40:14.639062+00:00 | 83 | false | \n**Approach 1 : Recursion (Include/Exclude Fashion)**\n\n*TLE Solution*\n```\nclass Solution {\npublic:\n int count;\n\t\n bool criteria_fulfilled(const vector<int>& result) {\n return (result[0] < result[1] && result[1] < result[2]) ||\n (result[0] > result[1] && result[1] > result[2]);\n }\n \n void solve(const vector<int>& rating, int curr_idx, int n, vector<int>& result) {\n if (result.size() == 3) {\n if (criteria_fulfilled(result)) {\n count++;\n }\n return; \n }\n\n if (curr_idx > n) {\n return;\n }\n\n // Include the current rating in the result\n result.push_back(rating[curr_idx]);\n solve(rating, curr_idx + 1, n, result);\n result.pop_back(); // Backtrack\n\n // Exclude the current rating and move to the next\n solve(rating, curr_idx + 1, n, result);\n }\n\n \n int numTeams(vector<int>& rating) {\n int n = rating.size() - 1;\n vector<int> result;\n count = 0;\n solve(rating , 0, n, result);\n \n return count;\n }\n};\n\n```\n\n**Approach 2 : Simple Combination Approach** \n\n**Basic Idea :**\nKeeping an element fixed, and looking for count of smaller elements on left side , and larger elements on right side and vice-versa. This problem now boils down to finding the number of combinations.\n\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size();\n\n int teams = 0;\n\n for(int j = 1; j < n-1; j++) {\n\n int countSmallerLeft = 0;\n int countLargerLeft = 0;\n int countSmallerRight = 0;\n int countLargerRight = 0;\n\n for(int i = 0; i < j; i++) {\n if(rating[i] < rating[j]) {\n countSmallerLeft++;\n } else if(rating[i] > rating[j]) {\n countLargerLeft++;\n }\n }\n\n for(int k = j+1; k < n; k++) {\n if(rating[j] < rating[k]) {\n countLargerRight++;\n } else if(rating[j] > rating[k]) {\n countSmallerRight++;\n }\n }\n\n teams += (countLargerLeft * countSmallerRight) + (countSmallerLeft * countLargerRight);\n\n\n }\n\n return teams;\n }\n};\n\n```\n | 5 | 0 | ['Array', 'Recursion', 'C'] | 0 |
count-number-of-teams | Easy C++ Solution | Simple approach | no trees no dp only maths | with Video Explanation | easy-c-solution-simple-approach-no-trees-3zcp | Video Solution\nhttps://youtu.be/rSd_8XRW6Us?si=5SzuMhNlCKotrcR1\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involve | Atharav_s | NORMAL | 2024-07-29T07:43:53.178701+00:00 | 2024-07-29T09:32:00.879120+00:00 | 506 | false | # Video Solution\nhttps://youtu.be/rSd_8XRW6Us?si=5SzuMhNlCKotrcR1\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves counting the number of teams of 3 soldiers that can be formed from an array of ratings such that the ratings of the soldiers form either an increasing or a decreasing sequence. The intuitive approach is to use three nested loops, where the middle loop iterates over each possible "middle" soldier of the team, and the inner loops count the number of soldiers to the left and right that satisfy the conditions for forming a team.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization:\n\n- Initialize teams to 0 to keep track of the number of valid teams.\n2. Outer Loop:\n\n- Iterate over each soldier as the middle soldier (index j) from 1 to n-2 (since we need at least one soldier on both sides).\n3. Inner Loops:\n\n- For each middle soldier j, count the number of soldiers to the left (i) that are smaller and larger.\n- Similarly, count the number of soldiers to the right (k) that are smaller and larger.\n4. Count Teams:\n\n- The number of valid increasing teams with j as the middle soldier is the product of the number of smaller soldiers on the left and larger soldiers on the right.\n- The number of valid decreasing teams with j as the middle soldier is the product of the number of larger soldiers on the left and smaller soldiers on the right.\n- Add these products to teams.\n# Complexity\n- Time complexity:$$O(n^3)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& ratings) {\n\n int n = ratings.size();\n\n int teams = 0;\n\n for(int j = 1; j<n-1;j++){\n\n int smallerLeft = 0;\n int largerRight = 0;\n int smallerRight = 0;\n int largerLeft = 0;\n\n for(int i=0;i<j;i++){\n\n if(ratings[i] > ratings[j]){\n largerLeft++;\n }else{\n smallerLeft++;\n }\n \n }\n\n for(int k =j+1;k<n;k++){\n\n if(ratings[k] > ratings[j]){\n largerRight++;\n }else{\n smallerRight++;\n }\n \n }\n\n teams += (smallerLeft * largerRight) + (largerLeft * smallerRight);\n \n }\n\n return teams;\n \n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
count-number-of-teams | C# Solution for Count Number of Teams Problem | c-solution-for-count-number-of-teams-pro-txqc | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind the optimized solution is to avoid a brute-force check of all trip | Aman_Raj_Sinha | NORMAL | 2024-07-29T04:09:49.430901+00:00 | 2024-07-29T04:09:49.430937+00:00 | 359 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the optimized solution is to avoid a brute-force check of all triplets, which would be computationally expensive (O(n^3)). Instead, we focus on breaking down the problem by leveraging the relationships between the soldiers\u2019 ratings. By counting how many soldiers before and after a given soldier have ratings lower or higher, we can efficiently determine the number of valid teams.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tCounting Smaller and Larger Ratings:\n\t\u2022\tFor each soldier considered as the middle one (j), count how many soldiers to the left have a smaller rating (leftLess) and how many have a larger rating (leftGreater).\n\t\u2022\tSimilarly, count how many soldiers to the right have a smaller rating (rightLess) and how many have a larger rating (rightGreater).\n2.\tForming Teams:\n\t\u2022\tFor each soldier j, calculate the number of increasing teams as leftLess * rightGreater.\n\t\u2022\tCalculate the number of decreasing teams as leftGreater * rightLess.\n3.\tSumming the Results:\n\t\u2022\tSum the valid increasing and decreasing teams for all soldiers to get the total number of valid teams.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tO(n^2):\n\t\u2022\tThe outer loop runs n times.\n\t\u2022\tFor each iteration of the outer loop, the two inner loops each run up to n-1 times, resulting in a total of O(n^2) operations.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tO(1):\n\t\u2022\tThe algorithm uses a fixed number of integer variables for counting and does not depend on the size of the input array. Thus, the space complexity is constant.\n\n# Code\n```\npublic class Solution {\n public int NumTeams(int[] rating) {\n int n = rating.Length;\n int count = 0;\n \n for (int j = 0; j < n; j++) {\n int leftLess = 0, leftGreater = 0;\n int rightLess = 0, rightGreater = 0;\n \n // Count soldiers with lower and higher ratings before soldier j\n for (int i = 0; i < j; i++) {\n if (rating[i] < rating[j]) {\n leftLess++;\n } else if (rating[i] > rating[j]) {\n leftGreater++;\n }\n }\n \n // Count soldiers with lower and higher ratings after soldier j\n for (int k = j + 1; k < n; k++) {\n if (rating[k] < rating[j]) {\n rightLess++;\n } else if (rating[k] > rating[j]) {\n rightGreater++;\n }\n }\n \n // Calculate valid increasing teams with j as the middle soldier\n count += leftLess * rightGreater;\n // Calculate valid decreasing teams with j as the middle soldier\n count += leftGreater * rightLess;\n }\n \n return count;\n }\n}\n``` | 5 | 0 | ['C#'] | 0 |
count-number-of-teams | Detailed explanation DP | Python | From "why" to "how" | detailed-explanation-dp-python-from-why-qx60h | I have used the bottom up approach for this problem. I will skip the introduction to the bottom up approach itself and focus more on how one should have guessed | whichislovely | NORMAL | 2022-03-14T19:19:59.264536+00:00 | 2022-03-14T19:21:12.014167+00:00 | 485 | false | I have used the bottom up approach for this problem. I will skip the introduction to the bottom up approach itself and focus more on how one should have guessed how to implement it. You should easily follow my thought flow and replicate it in other similar problems.\n\nIt is trivial that we would like to build something like dp[i][j] where i is the size of the team and j is something related to the number of available solders. Similar to famous 1/0 knapsack problem. But what exactly my our dp[i][j] would represent? \n\nIn order to answer the question in hand, let\'s have a look at the given example:\nrating = [2,5,3,4,1]\n\nFor now I will only describe the type of teams with increasing raknings for simplicity of the concept. Later we will easily expand it to decreasing rankings as well. let\'s consider that we have solders [2,5,3]. It\'s easy to show that all possible teams of size 2 are the following:\n2 5\n2 3\nIn the next step of dynamically calculating our dp we allow having another solder and our troop becomes [2,5,3,4]. Analysing the teams of 2 people and knowing that the rank of the next solder is 4 we can notice that we only care about the rank of the last person in the team to know whether we can make a group of 3 adding our next solder.\n2 **5** 4 (not possible to form)\n2 **3** 4 (possible to form)\nLet me repeat that again, we do not care about what ranks come before the last person in the team. We only care about 5 and 3 in our example. \n\nSo this gives us a hint that our dp[i][j] should have information about the number of groups of size i that ends with a person at j-th rank.\n\nNow let\'s think about what initial case we should start from. If we look at the dp[1][j] that is the number of groups of size 1 that can be created with the last person of rank j we can easily see that for each element there is only one possible team that includes the solder (him/her)self. So we can initialize our dp[1][j] = 1 for all j and starting from that dynamically calculate the number of teams that can be formed ending with solder j.\n\nPseudocode for dynamically calculating dp:\n```\niterate over size of teams from 1 to 3: (iterator i)\n\titerate over each solder: (iterator j)\n\t\titerate over each solder with lower index: (iterator k)\n\t\t\tif rank of solder > rank of solder with lower index: \n\t\t\t\tdp_inc[i][j] += dp_inc[i-1][k] # for increasing ranking\n\t\t\telse:\n\t\t\t\tdp_dec[i][j] += dp_dec[i-1][k] # for decreasing ranking\n```\t\t\t\t\nIn the end, after calculating dp_inc[3] and dp_dec[3] they both include the information about the number of teams of size 3 that can be created ending with the solder with index j. By summing up all possible number of teams we arrive to the needed output.\n\nThe compele solution:\n```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n dp_inc = [[0] * n for i in range(4)] \n dp_dec = [[0] * n for i in range(4)]\n for i in range(n):\n dp_inc[1][i] = 1\n dp_dec[1][i] = 1\n for i in range(2, 4):\n for j in range(n):\n for k in range(j):\n if rating[j] > rating[k]:\n dp_inc[i][j] += dp_inc[i-1][k]\n else:\n dp_dec[i][j] += dp_dec[i-1][k]\n return sum(dp_inc[3]) + sum(dp_dec[3])\n \n``` | 5 | 0 | ['Dynamic Programming'] | 0 |
count-number-of-teams | Python Solution | python-solution-by-revanthnamburu-vths | \nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n if len(rating)<3: \n return 0\n greater = defaultdict(int)\n | revanthnamburu | NORMAL | 2022-02-19T23:56:12.048769+00:00 | 2022-02-19T23:56:12.048796+00:00 | 728 | false | ```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n if len(rating)<3: \n return 0\n greater = defaultdict(int)\n lesser = defaultdict(int)\n for i in range(len(rating)-1):\n for j in range(i+1, len(rating)):\n if rating[i] < rating[j]:\n greater[i] += 1\n else:\n lesser[i] += 1\n ans = 0\n print(greater, lesser)\n for i in range(len(rating)-2):\n for j in range(i+1, len(rating)):\n if rating[i] < rating[j]:\n ans+=greater[j]\n else:\n ans+=lesser[j]\n return ans\n```\n**I hope that you\'ve found this useful.**\n**In that case, please upvote. It only motivates me to write more such posts\uD83D\uDE03**\nComment below if you have any queries. | 5 | 0 | ['Python'] | 1 |
count-number-of-teams | C++ O(n*n) Approach and Code Explanation , DP permutation | c-onn-approach-and-code-explanation-dp-p-tvdj | The Idea is to generate the ways the combination can form\nBrute force solution would be to use 3 loop to check the combination O(n^3)\n\nfor(int i=0;i<rating.s | imdavidrock | NORMAL | 2021-09-25T18:05:53.497832+00:00 | 2021-09-25T18:12:31.731692+00:00 | 390 | false | The Idea is to generate the ways the combination can form\nBrute force solution would be to use 3 loop to check the combination O(n^3)\n```\nfor(int i=0;i<rating.size();i++)\n\tfor(int j=0;j<i;j++)\n\t\tfor(int k=0;k<j;k++)\n\t\tcheck for the condition satifying + increase the count\n```\n\n**O(n^2) approach** ,actually use the permutation (DP) to count the ways\nTo satify the condition rating[i] < rating[j] < rating[k] \n\nTake 2 variable leftless and rightgreat\n\nwe have to count for each rating(pivot) , rating **less than** the left of **pivot** meaning **leftless** and rating **greater than** right to the **pivot** meaning **rightgreat** and mutliplying the count gives the permutaion to achieve the condition.\n\nleftless * rightgreat\n\nTake 2 variable leftgreat and rightless\n\nTo *satify the condition * rating[i] > rating[j] > rating[k] \nwe have to count for each rating(pivot) , rating **greater than** left of the **pivot** meaning **leftgreat** and rating **less than** right to the **pivot** meaning **rightless** and mutliplying the count gives the permutaion to achieve the condition\n\nleftgreat * rightless\nAdd both the results for each index , gives total count\n\n\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n \n int res =0;\n for(int i= 1;i<=rating.size()-1;i++)\n {\n int leftless = 0,leftgreat =0,rightless =0 ,rightgreat =0;\n \n for(int j=0;j<rating.size();j++)\n {\n if(rating[j]<rating[i])\n {\n if(j<i)\n {\n //left less\n leftless ++;\n }\n else if(j>i)\n {\n //right less\n rightless++;\n }\n }\n else if(rating[j]>rating[i])\n {\n if(j<i)\n leftgreat++;\n else if(j>i)\n rightgreat++;\n }\n }\n // [leftless rightgreat] satify rating[i] < rating[j] < rating[k]\n // [leftgreat,rightless] satify rating[i] > rating[j] > rating[k]\n //multiply give permutation/way of achieving that condition \n //adding give the total permutation for each index\n res += leftless*rightgreat +leftgreat*rightless;\n }\n return res;\n }\n};\n``` | 5 | 1 | ['Dynamic Programming'] | 0 |
count-number-of-teams | [Python] O(n^3), O(n^2), O(nlogn) solutions | python-on3-on2-onlogn-solutions-by-modus-07hq | \nfrom sortedcontainers import SortedList\n\nclass Solution:\n\n\t# O(n^3) bruteforce check all the indices\n def numTeams(self, rating: List[int]) -> int:\n | modusv | NORMAL | 2021-01-20T23:51:19.031563+00:00 | 2021-01-20T23:51:19.031635+00:00 | 698 | false | ```\nfrom sortedcontainers import SortedList\n\nclass Solution:\n\n\t# O(n^3) bruteforce check all the indices\n def numTeams(self, rating: List[int]) -> int:\n cnt = 0\n \n for i in range(len(rating)-2):\n for j in range(i+1, len(rating)-1):\n if rating[i] != rating[j]:\n for k in range(j+1, len(rating)):\n if (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]):\n cnt += 1\n return cnt \n \n\t# O(n^2 * k) but k is constant. Dynamic Programming bottom up one pass, it works also for k with higher values\n def numTeams(self, rating: List[int]) -> int: \n def inc_sub(arr, k):\n dp = [[[0,0] for i in range(len(arr))] for i in range(k)]\n \n for i in range(len(arr)): \n dp[0][i] = [1,1] \n \n for cl in range(1, k):\n for i in range(len(rating)):\n for j in range(cl-1, i):\n if arr[j] < arr[i]:\n dp[cl][i][0] += dp[cl-1][j][0]\n if arr[j] > arr[i]:\n dp[cl][i][1] += dp[cl-1][j][1]\n \n return sum(l1+l2 for l1, l2 in dp[-1]) \n return inc_sub(rating, 3)\n\n \n\t# O(n^2 * k) but k is constant. Dynamic Programming bottom up two passes, it works also for k with higher values\n def numTeams(self, rating: List[int]) -> int:\n def inc_sub(arr, k):\n dp = [[0 for i in range(len(arr))] for i in range(k)]\n \n for i in range(len(arr)): \n dp[0][i] = 1\n \n for cl in range(1, k):\n for i in range(len(rating)):\n for j in range(cl-1, i):\n if arr[j] < arr[i]:\n dp[cl][i] += dp[cl-1][j]\n \n return sum(dp[-1]) \n return inc_sub(rating, 3) + inc_sub(rating[::-1], 3)\n\n \n\t# O(nlogn), keep sorted left and right so we can find the insertion point with binary search. \n def numTeams(self, rating: List[int]) -> int:\n \n def indices(sl, x):\n return sl.bisect_left(x), len(sl) - sl.bisect_right(x)\n \n res = 0\n \n left = SortedList()\n right = SortedList(rating)\n \n for x in rating: \n right.remove(x)\n low_left, high_left = indices(left, x)\n low_righ, high_righ = indices(right, x)\n res += low_left * high_righ + high_left * low_righ\n left.add(x) \n return res\n``` | 5 | 0 | [] | 3 |
count-number-of-teams | C++ | O(n^2) | w/ comments | c-on2-w-comments-by-ialgorithm-g89b | \nclass Solution {\npublic:\n \n // For soldiers 1 to n-1\n // For soldiers 0 to n\n // We will keep track these things:\n // a = Cou | ialgorithm | NORMAL | 2020-07-24T23:02:32.108036+00:00 | 2020-07-31T01:29:37.979731+00:00 | 323 | false | ```\nclass Solution {\npublic:\n \n // For soldiers 1 to n-1\n // For soldiers 0 to n\n // We will keep track these things:\n // a = Count of ratings less than current on the left\n // b = Count of ratings less than current on the right\n // c = Count of ratings more than current on the left\n // d = Count of ratings more than current on the right\n\t// With current soldier in the "center" of the team:\n\t// We can have (a * d) teams with rating increasing from left to right\n\t// and (c * b) teams with rating decreasing from left to right\n // So the total number is ((a * d) + (c * b)) teams\n \n int numTeams(vector<int>& rating) {\n int teams = 0; // Total number of teams\n for(int i = 1; i < rating.size() - 1; ++i) {\n int a = 0, b = 0, c = 0, d = 0;\n for(int j = 0; j < rating.size(); ++j) {\n if(j < i) {\n if(rating[j] < rating[i]) a++;\n if(rating[j] > rating[i]) c++;\n } else if(j > i) {\n if(rating[j] < rating[i]) b++;\n if(rating[j] > rating[i]) d++;\n } else continue;\n }\n teams += ((a * d) + (c * b));\n }\n return teams;\n }\n``` | 5 | 0 | [] | 1 |
count-number-of-teams | [Python3] Fenwick Tree solution, O(n log(n)) (100%) | python3-fenwick-tree-solution-on-logn-10-povu | This is a solution based on the one from this post: https://leetcode.com/problems/count-number-of-teams/discuss/554907/Java-Detailed-Explanation-TreeSet-greater | skasch | NORMAL | 2020-07-23T16:05:17.073064+00:00 | 2020-07-23T16:06:40.278896+00:00 | 525 | false | This is a solution based on the one from this post: https://leetcode.com/problems/count-number-of-teams/discuss/554907/Java-Detailed-Explanation-TreeSet-greater-BIT-(Fenwick-Tree)-O(NlogN)\n\nI thought that this was a very interesting and efficient approach, but still wanted to improve upon it by reducing the size of the Fenwick Trees. The main idea is to build the Fenwick Tree on the "rank" of the ratings, i.e. the index of the ratings when sorted, which reduces the size of the Fenwick Tree from `N = 10^5`, the largest possible input, to `n`, the length of the array. Here\'s my Python solution.\n\nI reached 44ms (99.53%) with it.\n\n```\nclass BIT:\n\t"""A Binary Index Tree, a.k.a. Fenwick Tree."""\n \n def __init__(self, n: int):\n self.n = n\n self.bits = [0] * (n + 1)\n self.total = 0\n\t\t# Total stores the total sum of the tree. This makes retrieving right sums more efficient.\n \n def update(self, index: int, value: int):\n\t\t"""Add value `value` at index `index`: O(log(n))."""\n index += 1\n self.total += value\n while index <= self.n:\n self.bits[index] += value\n index += index & (-index)\n \n def getsum(self, index: int):\n\t\t"""Get the sum of values to the left of `index` if positive, or to the right if negative; O(log(n))."""\n if index < 0:\n\t\t\t# `~index == - index - 1`.\n\t\t\t# `bit.getsum(~index)` will retrieve the sum of values from `index + 1` to `n`.\n return self.total - self.getsum(~index)\n if index >= self.n:\n return self.total\n ans = 0\n index += 1\n while index > 0:\n ans += self.bits[index]\n index -= index & (-index)\n return ans\n\n\nclass Solution:\n\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n mapping = {r: i for i, r in enumerate(sorted(rating))}\n left_counts = BIT(n)\n right_counts = BIT(n)\n for r in rating[1:]:\n right_counts.update(mapping[r], 1)\n ans = 0\n left_counts.update(mapping[rating[0]], 1)\n for r in rating[1 : -1]:\n index = mapping[r]\n right_counts.update(index, -1)\n ans += left_counts.getsum(index) * right_counts.getsum(~index)\n ans += left_counts.getsum(~index) * right_counts.getsum(index)\n left_counts.update(index, 1)\n return ans\n```\n\nAn alternative solution, which is slightly more efficient (only two calls to `getsum` per loop, as opposed to four). I reached 36ms (100%) with it:\n\n```\nclass BIT:\n """A Binary Index Tree, a.k.a. Fenwick Tree."""\n \n def __init__(self, n: int):\n self.n = n\n self.bits = [0] * (n + 1)\n self.total = 0\n\t\t# Total stores the total sum of the tree. This makes retrieving right sums more efficient.\n \n def update(self, index: int, value: int):\n """Add value `value` at index `index`: O(log(n))."""\n index += 1\n self.total += value\n while index <= self.n:\n self.bits[index] += value\n index += index & (-index)\n \n def getsum(self, index: int):\n """Get the sum of values to the left of `index`; O(log(n))."""\n ans = 0\n index += 1\n while index > 0:\n ans += self.bits[index]\n index -= index & (-index)\n return ans\n\n\nclass Solution:\n\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n mapping = {r: i for i, r in enumerate(sorted(rating))}\n left_counts = BIT(n)\n right_counts = BIT(n)\n for r in rating[1:]:\n right_counts.update(mapping[r], 1)\n ans = 0\n left_counts.update(mapping[rating[0]], 1)\n for r in rating[1 : -1]:\n index = mapping[r]\n right_counts.update(index, -1)\n left_sum = left_counts.getsum(index)\n right_sum = right_counts.getsum(index)\n ans += left_sum * (right_counts.total - right_sum)\n ans += right_sum * (left_counts.total - left_sum)\n left_counts.update(index, 1)\n return ans\n``` | 5 | 0 | [] | 1 |
count-number-of-teams | O(n ^ 2) approach with a basic optimization with comments | on-2-approach-with-a-basic-optimization-ril7t | """\n#define lld long long int\n \n\nclass Solution {\npublic:\n int numTeams(vector& v) {\n int n = v.size();\n | reapedjuggler | NORMAL | 2020-06-30T08:27:02.376758+00:00 | 2020-06-30T08:27:02.376809+00:00 | 246 | false | """\n#define lld long long int\n \n\nclass Solution {\npublic:\n int numTeams(vector<int>& v) {\n int n = v.size();\n int ans =0;\n \n // basically what iam trying to do is count the no of small values behind me and larger values ahead of me\n // they will form a valid triplet\n \n // similarly elements which are larger behind me and smaller in front of me will form another valid triplet \n \n \n for(int i=0;i<n;i++){\n lld behind1 = 0 , ahead1 = 0 , behind2 = 0 , ahead2 = 0;\n \n for(int j = 0 ; j < i ; j++){\n if(v[i] > v[j])\n behind1++; \n else\n ahead1++; \n }\n \n for(int j = i + 1 ; j < n ; j++){\n if(v[i] > v[j])\n behind2++;\n else\n ahead2++; \n }\n \n ans += (behind1 * ahead2) + (ahead1 * behind2); // total pairs\n \n }\n return ans;\n }\n \n};\n\n""" | 5 | 0 | [] | 3 |
count-number-of-teams | [Java] Two solutions explained | java-two-solutions-explained-by-roka-hhhs | Bruteforce solution is straightforward. Just calculate all triplets.\nTime complexity is O(n ^ 3)\n\n\nclass Solution {\n public int numTeams(int[] rating) { | roka | NORMAL | 2020-06-06T14:15:55.281391+00:00 | 2020-06-06T14:15:55.281436+00:00 | 463 | false | Bruteforce solution is straightforward. Just calculate all triplets.\nTime complexity is O(n ^ 3)\n\n```\nclass Solution {\n public int numTeams(int[] rating) {\n int n = rating.length;\n int answer = 0;\n \n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n for (int g = j + 1; g < n; g++) {\n if (rating[i] < rating[j] && rating[j] < rating[g]\n || rating[i] > rating[j] && rating[j] > rating[g]) {\n answer++;\n }\n }\n }\n }\n \n return answer;\n }\n}\n```\n\nWe can eliminate one of loops with additional storage. For each index `i` calculate how many elements are bigger from left and how many elements are bigger from right. Store this computations in separate arrrays `numberOfBiggerFromLeft` and `numberOfBiggerFromRight`. Now, the answer is `sum(numberOfBiggerFromLeft[i] * numberOfSmallerFromRight[i] + numberOfSmallerFromLeft[i] * numberOfBiggerFromRight[i])` for each `0 < i < n` where `numberOfSmallerFromRight = n - i - 1 - numberOfBiggerFromRight[i]` and `numberOfSmallerFromLeft[i] = (i - numberOfBiggerFromLeft[i])`\n\n```\nclass Solution {\n public int numTeams(int[] rating) {\n int n = rating.length;\n int answer = 0;\n \n int[] numberOfBiggerFromLeft = new int[n];\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < i; j++) {\n if (rating[j] > rating[i]) {\n numberOfBiggerFromLeft[i]++;\n }\n }\n }\n \n int[] numberOfBiggerFromRight = new int[n];\n for (int i = 0; i + 1 < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (rating[j] > rating[i]) {\n numberOfBiggerFromRight[i]++;\n }\n }\n }\n \n for (int i = 0; i < n; i++) {\n int rightToLeft = numberOfBiggerFromLeft[i] * (n - 1 - i - numberOfBiggerFromRight[i]);\n int leftToRight = (i - numberOfBiggerFromLeft[i]) * numberOfBiggerFromRight[i];\n answer += rightToLeft + leftToRight;\n }\n \n return answer;\n }\n}\n``` | 5 | 0 | [] | 0 |
count-number-of-teams | 100 % faster cpp easy sol | 100-faster-cpp-easy-sol-by-patilc125-2xuj | class Solution {\npublic:\n int numTeams(vector& a) {\n int i,n=a.size(),sum=0;\n for(i=1;i=0;j--){\n if(a[i]>a[j]){\n | patilc125 | NORMAL | 2020-05-08T09:39:52.748300+00:00 | 2020-05-08T09:39:52.748350+00:00 | 788 | false | class Solution {\npublic:\n int numTeams(vector<int>& a) {\n int i,n=a.size(),sum=0;\n for(i=1;i<n-1;i++){\n int countgr=0,countlr=0,countgl=0,countll=0;\n for(int j=i-1;j>=0;j--){\n if(a[i]>a[j]){\n countgl++;\n }else{\n if(a[i]<a[j]){\n countll++;\n }\n }\n }\n \n for(int j=i+1;j<n;j++){\n if(a[i]<a[j]){\n countlr++;\n }else{\n if(a[i]>a[j]){\n countgr++;\n }\n }\n }\n \n sum+=(countll*countgr)+(countgl*countlr);\n \n }\n return sum;\n }\n}; | 5 | 2 | ['C', 'C++'] | 0 |
count-number-of-teams | C++ 8ms 100% | c-8ms-100-by-tushleo96-rxqa | \nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n \n int n = rating.size() ;\n \n int ans = 0 ;\n \n | tushleo96 | NORMAL | 2020-04-26T13:02:48.996846+00:00 | 2020-04-26T13:02:48.996879+00:00 | 437 | false | ```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n \n int n = rating.size() ;\n \n int ans = 0 ;\n \n for( int j=1 ; j<n-1 ; j++ ){\n \n int i_small = 0 , i_big = 0 , k_small = 0 , k_big = 0 ;\n \n for( int i=0 ; i<j ; i++ ){\n if(rating[i]<rating[j]) i_small++ ;\n else if(rating[i]>rating[j]) i_big++ ;\n }\n \n for( int k=j+1 ; k<n ; k++ ){\n if(rating[j]<rating[k]) k_big++ ;\n else if(rating[j]>rating[k]) k_small++ ;\n }\n \n ans += (i_small*k_big) + (i_big*k_small) ;\n \n }\n return ans ;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
count-number-of-teams | [C++] Aggregator of solutions (O(n^2),O(nlogn)) with real load testing -> find out the best | c-aggregator-of-solutions-on2onlogn-with-dsvn | People\'ve already published a lot of interesting solutions, I\'ve just gathered some of them, tuned the most optimal one, made a loading test and finally publi | dmitriy_philimonov | NORMAL | 2020-04-12T15:38:09.408301+00:00 | 2020-04-12T20:13:49.618082+00:00 | 393 | false | People\'ve already published a lot of interesting solutions, I\'ve just gathered some of them, tuned the most optimal one, made a loading test and finally published the results. After each approach the complexity/space is specified. Copyright is respected, all sources are specified :)\n\nMy loading test is quite simple (I had to move ui32->ui64 to prevent overlow):\n```\n using Solution=TSolutionOptimal; // change implementation here\n constexpr size_t n=1e5; std::vector<int> v(n);\n for(size_t i=0;i<n;++i) v[i]=i*117/71;\n Solution s; DEBUG(s.numTeams(v));\n```\nRun as (debug/sanitize):\n```\n$ g++ --std=c++2a -Wall -Werror -g -fsanitize=address -march=native count-number-of-teams.cpp -o runner && time ./runner\n```\nRun as (O3):\n```\n$ g++ --std=c++2a -Wall -Werror -O3 -march=native count-number-of-teams.cpp -o runner && time ./runner\n```\n\nMy output in all cases:\n```\ns.numTeams(v) = 166661666700000\n```\nTimimgs:\n1. Brute force: O(n^2)/O(1):\nTime(Debug/sanitize)=1m19s, Time(O3)=0m0.980s\n2. Tree approach: O(n log n)/O(n):\nTime(Debug/sanitize)=1m31s, Time(O3)=0m36.928s\n3. Map+Fenwick: O(n log n)/O(n):\nTime(Debug/sanitize)=0m0.171s, Time(O3)=0m0.025s\n4. Sort+Fenwick: O(n log n)/O(n):\nTime(Debug/sanitize)=0m0.069s, Time(O3)=0m0.009s\n\n=== Details and code: ===\n\n1. Brute force: O(n^2)/O(1)\n```cpp\nclass TSolutionBruteForce {\n using ui32=uint32_t;\n using ui64=uint64_t;\npublic:\n /* O(n^2) */\n ui64 numTeams(const std::vector<int>& rating) {\n const ui32 n=rating.size();\n struct T{\n ui32 Less=0;\n ui32 Greater=0;\n };\n ui64 cnt=0;\n for(ui32 mid=1;mid<n-1;++mid){\n ui32 midL=mid; int currR=rating[mid]; T lcurr;\n while(midL--){\n lcurr.Less += rating[midL]<currR;\n lcurr.Greater += rating[midL]>currR;\n }\n ui32 midR=mid; T rcurr;\n while(++midR<n){\n rcurr.Less += rating[midR]<currR;\n rcurr.Greater += rating[midR]>currR;\n }\n cnt+=lcurr.Less*rcurr.Greater+lcurr.Greater*rcurr.Less;\n }\n return cnt;\n }\n};\n```\nTime(Debug/sanitize)=1m19s, Time(O3)=0m0.980s\n\n2. Tree approach: O(n log n)/O(n) // actually copy-paste from votrubac post, details see in the original source: https://leetcode.com/problems/count-number-of-teams/discuss/554795/C%2B%2BJava-O(n--n)-and-O(n-log-n)\n```cpp\nclass TSolutionTree{\n using ui32=uint32_t;\n using ui64=uint64_t;\n struct Tree {\n Tree *left = nullptr, *right = nullptr;\n int val = 0, cnt_left = 0;\n Tree(int val) : val(val) {}\n };\n ui32 count(Tree* root, int val) {\n if (root == nullptr)\n return 0;\n if (val < root->val)\n return count(root->left, val);\n return 1 + root->cnt_left + count(root->right, val);\n }\n Tree* insert(Tree* root, int val) {\n if (root == nullptr)\n return new Tree(val);\n if (val < root->val) {\n ++root->cnt_left;\n root->left = insert(root->left, val);\n }\n else\n root->right = insert(root->right, val);\n return root;\n }\n Tree* remove(Tree* root, int val) {\n if (root == nullptr)\n return nullptr;\n if (root->val == val) {\n if (root->left == nullptr)\n return root->right;\n auto rightmost = root->left;\n while (rightmost->right != nullptr)\n rightmost = rightmost->right;\n rightmost->right = root->right;\n return root->left;\n }\n if (val < root->val) {\n --root->cnt_left;\n root->left = remove(root->left, val);\n }\n else\n root->right = remove(root->right, val);\n return root;\n }\npublic:\n /* O(n log n) */\n ui64 numTeams(const std::vector<int>& rating) {\n Tree left(rating.front()), right(rating.back());\n ui64 res = 0; ui32 sz = rating.size();\n for (ui32 i = 1; i < sz - 1; ++i)\n insert(&right, rating[i]);\n for (ui32 i = 1; i < sz - 1; ++i) {\n remove(&right, rating[i]);\n ui32 l_sm = count(&left, rating[i]), l_lg = i - l_sm;\n ui32 r_sm = count(&right, rating[i]), r_lg = (sz - 1 - i - r_sm);\n res += l_sm * r_lg + l_lg * r_sm;\n insert(&left, rating[i]);\n }\n return res;\n }\n};\n```\nTime(Debug/sanitize)=1m31s, Time(O3)=0m36.928s (yeah, the solution leaks, no deletes in my version, probably fixed in the original post; I was interested in performance only and it\'s quite awful, so decided not to fix by myself, sorry)\n\n3. Map+Fenwick: O(n log n)/O(n). Copy-paste from: https://leetcode.com/problems/count-number-of-teams/discuss/555196/C%2B%2B-solutions-O(n-3)-O(n-2)-and-O(nlogn)\n```cpp\nclass TSolutionOptimalOriginal {\n using ui32=uint32_t;\n using ui64=uint64_t;\n void update(std::vector<ui32> &v, ui32 i, const ui32 d) {\n for (; i < v.size(); v[i] += d, i += (i & -i));\n }\n\n ui32 presum(const std::vector<ui32> &v, ui32 i) {\n ui32 r = 0;\n for (; i; r += v[i], i -= (i & -i));\n return r;\n }\n\npublic:\n /* O(n log n) */\n ui64 numTeams(const std::vector<int>& rating) {\n std::map<int, ui32> have;\n for (int x : rating) {\n have[x];\n }\n ui32 n = 0;\n std::vector<ui32> after(rating.size() + 1);\n for (auto& t : have) {\n update(after, t.second = ++n, 1);\n }\n std::vector<ui32> before(n + 1);\n ui64 r = 0;\n for (ui32 i = 0; i < n; ++i) {\n const ui32 x = have[rating[i]], t1 = presum(before, x), t2 = presum(after, x);\n r += t1 * (n - i - t2) + (i - t1) * (t2 - 1);\n update(after, x, -1);\n update(before, x, 1);\n }\n return r;\n }\n};\n```\nTime(Debug/sanitize)=0m0.171s, Time(O3)=0m0.025s\n\n4. Sort+Fenwick: O(n log n)/O(n). Actually it\'s the tuned 3 version. std::map->std::sort+binary_search\n```cpp\nclass TSolutionOptimal {\n using ui32=uint32_t;\n using ui64=uint64_t;\n void update(std::vector<ui32>& v, ui32 i, ui32 val){\n while(i<v.size()){ v[i]+=val; i+=i&(-i); }\n }\n ui32 read(const std::vector<ui32>& v, ui32 i){\n ui32 sum=0; while(i>0){ sum+=v[i]; i-=i&(-i); }\n return sum;\n }\n ui32 find(const std::vector<int>& v, int val){\n ui32 b=0,e=v.size()-1;\n while(b<e){\n ui32 mid=b+(e-b)/2;\n if(v[mid]<val){\n b=mid+1; continue;\n }\n if(v[mid]>val){\n e=mid-1; continue;\n }\n return mid;\n }\n return b;\n }\npublic:\n /* O(n log n) */\n ui64 numTeams(const std::vector<int>& rating) {\n const ui32 n=rating.size();\n\n std::vector<int> sorted(rating.begin(),rating.end());\n std::sort(sorted.begin(),sorted.end());\n\n std::vector<ui32> before(n+1),after(n+1);\n for(ui32 x=1;x<=n;++x) update(after,x,1);\n\n ui64 cnt=0;\n for(ui32 i=0;i<n;++i){\n int x=1+find(sorted,rating[i]), b=read(before,x), a=read(after,x);\n cnt+=b*(n-i-a)+(i-b)*(a-1);\n update(before,x,1); update(after,x,-1);\n }\n return cnt;\n }\n};\n```\nTime(Debug/sanitize)=0m0.069s, Time(O3)=0m0.009s\n\nResume: cache-friendly approaches rule the world, the difference could be more than 2 times. | 5 | 0 | [] | 0 |
count-number-of-teams | C++ lis | c-lis-by-wufengxuan1230-69su | \nclass Solution {\npublic:\n int count(vector<int>& rating)\n {\n int res = 0;\n vector<int> less(rating.size());\n for(int i = 1; i | wufengxuan1230 | NORMAL | 2020-04-05T04:25:55.146293+00:00 | 2020-04-08T23:20:35.196457+00:00 | 308 | false | ```\nclass Solution {\npublic:\n int count(vector<int>& rating)\n {\n int res = 0;\n vector<int> less(rating.size());\n for(int i = 1; i < rating.size(); i++)\n {\n for(int j = 0; j < i; j++)\n {\n if(rating[j] < rating[i])\n {\n less[i]++;\n res += less[j];\n }\n }\n }\n return res;\n }\n \n int numTeams(vector<int>& rating) \n {\n int res = count(rating);\n reverse(rating.begin(), rating.end());\n return res + count(rating);\n }\n};\n``` | 5 | 0 | [] | 1 |
count-number-of-teams | C++ O(NlogN) Mergesort | c-onlogn-mergesort-by-leetcode1024-oleu | Solution\n\ndraw lessons from Leetcode315 Count of Smaller Numbers After Self\uFF0C we can using Mergesort\nt0 means the number of Smaller Numbers After Self\nt | Leetcode1024 | NORMAL | 2020-03-29T10:57:10.212556+00:00 | 2020-03-29T10:57:10.212603+00:00 | 272 | false | ### Solution\n\ndraw lessons from Leetcode315 Count of Smaller Numbers After Self\uFF0C we can using Mergesort\nt0 means the number of Smaller Numbers After Self\nt1 means the number of Bigger Numbers After Self\n\n### Code\n\n```cpp\nclass SolutionOfLeetCode315 {\npublic:\n using pii = pair<int, int>;\n vector<vector<int>> countSmaller(vector<int>& nums) {\n int n = nums.size();\n vector<pii> v(n);\n vector<vector<int>> res(2, vector<int>(n, 0));\n for (int i = 0; i < n; i++) v[i] = {nums[i], i}; \n merge_sort(v.begin(), v.end(), res, true); \n for (int i = 0; i < n; i++) v[i] = {nums[i], i}; \n merge_sort(v.begin(), v.end(), res, false);\n return res;\n }\nprivate:\n void merge_sort(vector<pii>::iterator l, vector<pii>::iterator r,\n vector<vector<int>> &res, bool IsGreater) {\n if (l+1 < r) {\n auto mid = l + (r-l)/2;\n merge_sort(l, mid, res, IsGreater);\n merge_sort(mid, r, res, IsGreater);\n merge(l, r, res, IsGreater);\n } \n }\n \n void merge(vector<pii>::iterator l, vector<pii>::iterator r, \n vector<vector<int>> &res, bool IsGreater) {\n int cnt = 0;\n auto mid = l + (r-l)/2, p = l, q = mid;\n while (p < mid || q < r) {\n if (p < mid && q < r) {\n if (q->first >= p->first) {\n if (!IsGreater) res[1][p->second] += r-q;\n IsGreater ? ++q : ++p;\n }\n else {\n if (IsGreater) res[0][p->second] += r-q;\n IsGreater ? ++p : ++q;\n }\n }\n else if (p < mid) p++;\n else q++;\n }\n if (IsGreater) inplace_merge(l, mid, r, std::greater<>());\n else inplace_merge(l, mid, r, std::less<>());\n }\n};\n\n\n\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n //preprocess\n class SolutionOfLeetCode315 A;\n auto temp = A.countSmaller(rating);\n auto &t0 = temp[0], t1 = temp[1];\n \n int n = rating.size(), res = 0;\n vector<int> sorted_rating(rating);\n sort(sorted_rating.begin(), sorted_rating.end());\n \n for (int i = 1; i < n-1; ++i) {\n int pos = lower_bound(sorted_rating.begin(), sorted_rating.end(), rating[i]) \n - sorted_rating.begin(); \n res += t0[i]*(n-1-pos-t1[i]) + t1[i]*(pos-t0[i]);\n }\n return res;\n }\n};\n\n\n``` | 5 | 0 | [] | 1 |
count-number-of-teams | Easy Approach | easy-approach-by-manju_bodi-vdgw | Intuition\n Describe your first thoughts on how to solve this problem. \nInstead of checking all possible triplets, which would be computationally expensive (O( | Manju_Bodi | NORMAL | 2024-07-30T17:46:11.622379+00:00 | 2024-07-30T17:46:11.622404+00:00 | 99 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInstead of checking all possible triplets, which would be computationally expensive (O(n^3)), the code uses a more efficient approach by iterating over each possible middle element and counting potential valid configurations.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate Over Each Element as Middle Element (rating[i]):\nFor each element in the list, treat it as the middle element of the triplet. The goal is to determine how many valid triplets can be formed with this element as the middle element.\n\n2. Count Elements Less Than and Greater Than the Middle Element:\nFor the current middle element rating[i]:\nCount left: Number of elements before i that are less than rating[i]. This counts how many smaller elements can be a part of an increasing sequence where rating[i] is the middle element.\nCount right: Number of elements after i that are greater than rating[i]. This counts how many larger elements can follow rating[i] to form a valid increasing sequence.\nMultiply these counts to get the number of valid increasing triplets with rating[i] as the middle element.\n\n3. Count Elements Greater Than and Less Than the Middle Element:\nSimilarly:\nCount left: Number of elements before i that are greater than rating[i]. This counts how many larger elements can be a part of a decreasing sequence where rating[i] is the middle element.\nCount right: Number of elements after i that are less than rating[i]. This counts how many smaller elements can follow rating[i] to form a valid decreasing sequence.\nMultiply these counts to get the number of valid decreasing triplets with rating[i] as the middle element.\n\n4. Update Total Count (ans):\nSum up the counts from both increasing and decreasing sequences for each element to get the total number of valid teams.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the given solution is \uD835\uDC42(\uD835\uDC5B^2). This is because for each element (total \uD835\uDC5B elements), we perform two passes to count elements before and after it. Each pass involves iterating through parts of the list, resulting in \uD835\uDC42(\uD835\uDC5B^2) operations in total.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is \uD835\uDC42(1) because we use only a few extra variables (e.g., ans, left, right) regardless of the input size. No additional space is used that scales with input size.\n\n# Code\n```python []\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n ans=0\n n=len(rating)\n for i in range(n):\n left=sum(1 for j in range(i) if rating[i]<rating[j])\n right=sum(1 for j in range(i+1,n) if rating[i]>rating[j])\n ans+=left*right\n left=sum(1 for j in range(i) if rating[i]>rating[j])\n right=sum(1 for j in range(i+1,n) if rating[i]<rating[j])\n ans+=left*right\n return ans\n```\n```java []\nclass Solution {\n public int numTeams(List<Integer> rating) {\n int ans = 0;\n int n = rating.size();\n \n for (int i = 0; i < n; i++) {\n // Count how many elements to the left are smaller than rating[i]\n int left = 0;\n for (int j = 0; j < i; j++) {\n if (rating.get(i) < rating.get(j)) {\n left++;\n }\n }\n // Count how many elements to the right are larger than rating[i]\n int right = 0;\n for (int j = i + 1; j < n; j++) {\n if (rating.get(i) > rating.get(j)) {\n right++;\n }\n }\n ans += left * right;\n \n // Count how many elements to the left are larger than rating[i]\n left = 0;\n for (int j = 0; j < i; j++) {\n if (rating.get(i) > rating.get(j)) {\n left++;\n }\n }\n // Count how many elements to the right are smaller than rating[i]\n right = 0;\n for (int j = i + 1; j < n; j++) {\n if (rating.get(i) < rating.get(j)) {\n right++;\n }\n }\n ans += left * right;\n }\n \n return ans;\n }\n}\n\n```\n```cpp []\n#include <vector>\n\nclass Solution {\npublic:\n int numTeams(std::vector<int>& rating) {\n int ans = 0;\n int n = rating.size();\n \n for (int i = 0; i < n; i++) {\n int left = 0, right = 0;\n \n // Count how many elements to the left are smaller than rating[i]\n for (int j = 0; j < i; j++) {\n if (rating[i] < rating[j]) {\n left++;\n }\n }\n // Count how many elements to the right are larger than rating[i]\n for (int j = i + 1; j < n; j++) {\n if (rating[i] > rating[j]) {\n right++;\n }\n }\n ans += left * right;\n \n // Count how many elements to the left are larger than rating[i]\n left = 0;\n for (int j = 0; j < i; j++) {\n if (rating[i] > rating[j]) {\n left++;\n }\n }\n // Count how many elements to the right are smaller than rating[i]\n right = 0;\n for (int j = i + 1; j < n; j++) {\n if (rating[i] < rating[j]) {\n right++;\n }\n }\n ans += left * right;\n }\n \n return ans;\n }\n};\n\n```\n```c []\n#include <stdio.h>\n\nint numTeams(int* rating, int ratingSize) {\n int ans = 0;\n \n for (int i = 0; i < ratingSize; i++) {\n int left = 0, right = 0;\n \n // Count how many elements to the left are smaller than rating[i]\n for (int j = 0; j < i; j++) {\n if (rating[i] < rating[j]) {\n left++;\n }\n }\n // Count how many elements to the right are larger than rating[i]\n for (int j = i + 1; j < ratingSize; j++) {\n if (rating[i] > rating[j]) {\n right++;\n }\n }\n ans += left * right;\n \n // Count how many elements to the left are larger than rating[i]\n left = 0;\n for (int j = 0; j < i; j++) {\n if (rating[i] > rating[j]) {\n left++;\n }\n }\n // Count how many elements to the right are smaller than rating[i]\n right = 0;\n for (int j = i + 1; j < ratingSize; j++) {\n if (rating[i] < rating[j]) {\n right++;\n }\n }\n ans += left * right;\n }\n \n return ans;\n}\n\n``` | 4 | 0 | ['Array', 'C', 'C++', 'Java', 'Python3'] | 0 |
count-number-of-teams | Binary Search O(nlogn) Approach (Without DP/ Tree) ๐ฅ | binary-search-onlogn-approach-without-dp-9zyl | Intuition\nThe solution can be found by calculating the number of previous and next smaller and greater elements. \nBinary Search can give place of element in a | dmxsharma | NORMAL | 2024-07-29T22:52:37.661093+00:00 | 2024-07-29T22:52:37.661114+00:00 | 44 | false | # Intuition\nThe solution can be found by calculating the number of previous and next smaller and greater elements. \nBinary Search can give place of element in a sorted array which is basically number of previous smaller elements.\nManipulating it we can find rest three also.\n\n# Approach\nThe helper function will use lower bound implementation of inbuilt C++ stlto calculate desired vector which stores number of previous smaller elements and further 3 similar implementations.\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> prevSmaller(vector<int>& nums) {\n int n = nums.size();\n vector<int> temp;\n vector<int> ans(n);\n\n for (int i = 0; i < n; i++) {\n int lb =\n lower_bound(temp.begin(), temp.end(), nums[i]) - temp.begin();\n temp.insert(temp.begin() + lb, nums[i]);\n ans[i] = lb;\n }\n\n return ans;\n }\n\n vector<int> prevGreater(vector<int>& nums) {\n int n = nums.size();\n vector<int> temp;\n vector<int> ans(n);\n\n for (int i = 0; i < n; i++) {\n int lb =\n lower_bound(temp.begin(), temp.end(), nums[i]) - temp.begin();\n temp.insert(temp.begin() + lb, nums[i]);\n ans[i] = i - lb;\n }\n\n return ans;\n }\n\n vector<int> nextGreater(vector<int>& nums) {\n int n = nums.size();\n vector<int> temp;\n vector<int> ans(n);\n\n for (int i = n - 1; i >= 0; i--) {\n int lb =\n lower_bound(temp.begin(), temp.end(), nums[i]) - temp.begin();\n temp.insert(temp.begin() + lb, nums[i]);\n ans[i] = n - 1 - i - lb;\n }\n\n return ans;\n }\n\n vector<int> nextSmaller(vector<int>& nums) {\n int n = nums.size();\n vector<int> temp;\n vector<int> ans(n);\n\n for (int i = n - 1; i >= 0; i--) {\n int lb =\n lower_bound(temp.begin(), temp.end(), nums[i]) - temp.begin();\n temp.insert(temp.begin() + lb, nums[i]);\n ans[i] = lb;\n }\n\n return ans;\n }\n\n int numTeams(vector<int>& rating) {\n vector<int> prevSmall = prevSmaller(rating);\n vector<int> prevGreat = prevGreater(rating);\n vector<int> nextSmall = nextSmaller(rating);\n vector<int> nextGreat = nextGreater(rating);\n\n int count = 0;\n for (int i = 1; i < rating.size() - 1; i++) {\n count +=\n (prevSmall[i] * nextGreat[i]) + (prevGreat[i] * nextSmall[i]);\n }\n return count;\n }\n};\n``` | 4 | 0 | ['Array', 'Binary Search', 'C++'] | 1 |
count-number-of-teams | Count Number of Teams | count-number-of-teams-by-disinfect1936-tc9s | I\'ll answer as a world-renowned algorithm design expert with the prestigious ACM SIGACT G\xF6del Prize in Theoretical Computer Science\n\n# Intuition\n\nThe ke | Disinfect1936 | NORMAL | 2024-07-29T14:08:07.712744+00:00 | 2024-07-29T14:08:07.712782+00:00 | 139 | false | I\'ll answer as a world-renowned algorithm design expert with the prestigious ACM SIGACT G\xF6del Prize in Theoretical Computer Science\n\n# Intuition\n\nThe key insight for this problem is to realize that we can solve it efficiently by focusing on each soldier as the middle member of a potential team. For each soldier, we need to count how many valid combinations exist with them in the middle position.\n\n# Approach\n\n1. Iterate through each soldier (index j) as the potential middle member of a team.\n\n2. For each middle soldier, count:\n - Number of soldiers on the left with lower ratings (left_smaller)\n - Number of soldiers on the left with higher ratings (left_larger)\n - Number of soldiers on the right with lower ratings (right_smaller)\n - Number of soldiers on the right with higher ratings (right_larger)\n\n3. Calculate the number of valid teams for this middle soldier:\n - Teams where rating[i] < rating[j] < rating[k]: left_smaller * right_larger\n - Teams where rating[i] > rating[j] > rating[k]: left_larger * right_smaller\n\n4. Sum up these counts for all possible middle soldiers to get the total number of valid teams.\n\n# Complexity\n\n- Time complexity: $$O(n^2)$$\n Where n is the number of soldiers. We iterate through each soldier as the middle soldier (n-2 times), and for each, we scan all other soldiers to count the smaller and larger ratings on both sides.\n\n- Space complexity: $$O(1)$$\n We only use a constant amount of extra space for our counting variables, regardless of the input size.\n\nThis solution efficiently solves the problem without using any additional data structures, making it both time and space optimal for the given constraints (3 <= n <= 1000).\n\n# Code\n```\nclass Solution:\n def numTeams(self, rating: List[int]) -> int:\n n = len(rating)\n count = 0\n \n for j in range(1, n - 1):\n left_smaller = left_larger = right_smaller = right_larger = 0\n \n # Count soldiers on the left\n for i in range(j):\n if rating[i] < rating[j]:\n left_smaller += 1\n elif rating[i] > rating[j]:\n left_larger += 1\n \n # Count soldiers on the right\n for k in range(j + 1, n):\n if rating[k] < rating[j]:\n right_smaller += 1\n elif rating[k] > rating[j]:\n right_larger += 1\n \n # Calculate valid teams\n count += left_smaller * right_larger + left_larger * right_smaller\n \n return count\n\n``` | 4 | 0 | ['Array', 'Dynamic Programming', 'Binary Indexed Tree', 'Python3'] | 0 |
count-number-of-teams | C++ | Count Number of Teams with O(nยฒ) Complexity | Efficient 23ms Solution | c-count-number-of-teams-with-on2-complex-d7or | Intuition\nTo solve the problem of counting valid teams of 3 soldiers, we iterate over each soldier as the middle one, then count how many soldiers before it ar | user4612MW | NORMAL | 2024-07-29T03:24:26.403221+00:00 | 2024-07-29T03:24:26.403253+00:00 | 16 | false | # Intuition\nTo solve the problem of counting valid teams of 3 soldiers, we iterate over each soldier as the middle one, then count how many soldiers before it are smaller or larger and how many soldiers after it are smaller or larger. Using these counts, we calculate the number of valid triplets (i, j, k) that satisfy either **rating[i] < rating[j] < rating[k]** or **rating[i] > rating[j] > rating[k]**, ensuring **0 <= i < j < k < n**. This approach efficiently counts the valid teams by leveraging nested loops to fix the middle soldier and count possible preceding and succeeding soldiers.\n\n# Approach\nFor each soldier **j**, count the number of soldiers **i** before **j** that are either smaller or larger than **rating[j]**, and count the number of soldiers **k** after **j** that are either smaller or larger than **rating[j]**. Combine these counts to calculate the total number of valid teams where **(rating[i] < rating[j] < rating[k])** or **(rating[i] > rating[j] > rating[k])**.\n\n# Complexity\n- Time complexity $$O(n^2)$$ due to the nested loops iterating through the soldiers.\n- Space complexity $$O(1)$$ as we are using a constant amount of extra space.\n\n# Code\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n int n = rating.size(),totalTeams{0};\n for (int j{0}; j < n; ++j) {\n int leftSmaller{0}, leftLarger{0}, rightSmaller{0}, rightLarger{0};\n for (int i{0}; i < j; ++i) {\n if (rating[i] < rating[j]) ++leftSmaller;\n else if (rating[i] > rating[j]) ++leftLarger;\n }\n for (int k = j + 1; k < n; ++k) {\n if (rating[k] < rating[j]) ++rightSmaller;\n else if (rating[k] > rating[j]) ++rightLarger;\n }\n totalTeams += leftSmaller * rightLarger + leftLarger * rightSmaller;\n }\n return totalTeams;\n }\n};\n\n```\n**Example 1:** **rating = [2,5,3,4,1]** outputs **3** with valid teams (2, 3, 4), (5, 4, 1), and (5, 3, 1) for increasing or decreasing sequences; **Example 2:** **rating = [2,1,3]** outputs **0** as no valid teams exist; **Example 3:** **rating = [1,2,3,4]** outputs **4** with valid teams (1, 2, 3), (1, 2, 4), (1, 3, 4), and (2, 3, 4) for increasing sequences.\n\n## **If you found this solution helpful, please upvote! \uD83D\uDE0A** | 4 | 0 | ['C++'] | 0 |
count-number-of-teams | C++ || Easy Video Solution | c-easy-video-solution-by-n_i_v_a_s-szpb | The video solution for the below code is\nhttps://youtu.be/e6_F4VMr6XU\n\n# Code\n\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n | __SAI__NIVAS__ | NORMAL | 2024-07-29T01:47:19.267871+00:00 | 2024-07-29T01:47:19.267897+00:00 | 1,833 | false | The video solution for the below code is\nhttps://youtu.be/e6_F4VMr6XU\n\n# Code\n```\nclass Solution {\npublic:\n int numTeams(vector<int>& rating) {\n // 2 5 3 4 1\n // Condition - 1\n // 2 3 4\n // Condition - 2\n // 5 3 1\n // 5 4 1\n // Smallest numbers and largest numbers\n // Rating : 2 5 3 4 1 // x 3 4 - 1\n // Smallest : 0 1 1 2 0 // x 3 1 - 1\n // Largest : 0 0 1 1 4 // x 4 1 - 1\n int n = rating.size();\n vector<int> smallest(n, 0);\n vector<int> largest(n, 0);\n for(int i = 0 ; i < n ; i++){\n for(int j = i - 1 ; j >= 0 ; j--){\n if(rating[i] > rating[j]) smallest[i]++;\n if(rating[i] < rating[j]) largest[i]++;\n }\n }\n int ans = 0;\n for(int i = 0 ; i < n ; i++){\n for(int j = i - 1 ; j >= 0 ; j--){\n if(rating[i] > rating[j]) ans += smallest[j];\n if(rating[i] < rating[j]) ans += largest[j];\n }\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['C++'] | 2 |
count-number-of-teams | C++ || Fenwick Tree | c-fenwick-tree-by-nisamey-1cnm | ```\n void add(int N,vector&Fen){\n while(N < Fen.size()){\n Fen[N]++;\n N += (N)&(-N);\n }\n \n return;\n | Nisamey | NORMAL | 2022-08-19T09:09:19.333618+00:00 | 2022-08-19T09:09:19.333652+00:00 | 446 | false | ```\n void add(int N,vector<int>&Fen){\n while(N < Fen.size()){\n Fen[N]++;\n N += (N)&(-N);\n }\n \n return;\n }\n \n int getVal(int N,vector<int>&Fen){\n int res = 0;\n \n while(N > 0){\n res += Fen[N];\n N -= (N)&(-N);\n }\n \n return res;\n }\n \n int numTeams(vector<int>& rating) {\n vector<int> Fen(100001,0);\n \n vector<int> Sorted = rating;\n sort(Sorted.begin(),Sorted.end());\n \n int Ans = 0;\n int cnt = 0;\n int N = rating.size();\n \n for(auto x:rating){\n cnt++;\n \n int val = getVal(x,Fen);\n int ind = lower_bound(Sorted.begin(),Sorted.end(),x) - Sorted.begin();\n int rem = N - ind - (cnt - val);\n \n add(x,Fen);\n \n Ans += val*(rem); // for i < j < k\n Ans += (cnt - val - 1)*(N - cnt - rem); // for i > j > k\n }\n \n return Ans;\n }\n\t | 4 | 0 | ['Tree'] | 2 |
Subsets and Splits