Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SuryaPratapK/14a126a5ab8820af2c2d48dd4e0500ac to your computer and use it in GitHub Desktop.
Save SuryaPratapK/14a126a5ab8820af2c2d48dd4e0500ac to your computer and use it in GitHub Desktop.
class Solution {
public:
int countCompleteSubarrays(vector<int>& nums) {
unordered_set<int> unique_elements(nums.begin(),nums.end());
int unique_count = unique_elements.size();
int left = 0;
int right = 0;
int n = nums.size();
unordered_map<int,int> freq;
int complete_subarrays = 0;
while(left<n){
while(right<n and freq.size()<unique_count){
freq[nums[right]]++;
right++;
}
if(freq.size()<unique_count)
break;
complete_subarrays += n-right+1;
//Remove left
freq[nums[left]]--;
if(freq[nums[left]]==0)
freq.erase(nums[left]);
left++;
}
return complete_subarrays;
}
};
/*
//JAVA
import java.util.*;
class Solution {
public int countCompleteSubarrays(int[] nums) {
Set<Integer> uniqueElements = new HashSet<>();
for (int num : nums) {
uniqueElements.add(num);
}
int uniqueCount = uniqueElements.size();
int left = 0;
int right = 0;
int n = nums.length;
Map<Integer, Integer> freq = new HashMap<>();
int completeSubarrays = 0;
while (left < n) {
while (right < n && freq.size() < uniqueCount) {
freq.put(nums[right], freq.getOrDefault(nums[right], 0) + 1);
right++;
}
if (freq.size() < uniqueCount) {
break;
}
completeSubarrays += n - right + 1;
// Remove left
freq.put(nums[left], freq.get(nums[left]) - 1);
if (freq.get(nums[left]) == 0) {
freq.remove(nums[left]);
}
left++;
}
return completeSubarrays;
}
}
#Python
class Solution:
def countCompleteSubarrays(self, nums: List[int]) -> int:
unique_elements = set(nums)
unique_count = len(unique_elements)
left = 0
right = 0
n = len(nums)
freq = {}
complete_subarrays = 0
while left < n:
while right < n and len(freq) < unique_count:
freq[nums[right]] = freq.get(nums[right], 0) + 1
right += 1
if len(freq) < unique_count:
break
complete_subarrays += n - right + 1
# Remove left
freq[nums[left]] -= 1
if freq[nums[left]] == 0:
del freq[nums[left]]
left += 1
return complete_subarrays
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment