Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions week11/longest_substring_with_atmost_k_distinct_characters.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Time complexity: O(N), N = string length
// Space complexity: O(N), N = string length
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use vector<int> chrMap(256, 0) and bring down the MC to O(1).


int lengthOfLongestSubstringKDistinct(string s, int k){
unordered_map<char, int> chrMap;
int max_substring_length = 0;
int left = 0;
int string_length = s.length();
int num_of_distincts = 0;

for(int right = 0; right < string_length; right++){
if(chrMap.count(s[right]) == 0) num_of_distincts++;

chrMap[s[right]]++;

while(num_of_distincts > k){
if(chrMap[s[left]] > 1) chrMap[s[left]]--;
else{
chrMap.erase(s[left]);
num_of_distincts--;
}
left++;
}
max_substring_length = max(max_substring_length, right - left + 1);
}

return max_substring_length;
}
27 changes: 27 additions & 0 deletions week11/longest_substring_without_repeating_characters.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Time complexity: O(N) , N = Length of the given string.
// Space complexity: O(1)

int lengthOfLongestSubstring(string s){
int longestSubstringLength = 0;
vector<int> characterCount(256, 0);
int left = 0;
int right = 0;
int duplicateCount = 0;
int strLen = s.length();
while(right < strLen){
characterCount[s[right]]++;
if(characterCount[s[right]] > 1){
duplicateCount++;
}
right++;
while(duplicateCount > 0){
characterCount[s[left]]--;
if(characterCount[s[left]] == 1){
duplicateCount--;
}
left++;
}
longestSubstringLength = max(longestSubstringLength, right - left);
}
return longestSubstringLength;
}
22 changes: 22 additions & 0 deletions week11/subarray_sum_divisible_by_k.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Time complexity: O(N), N = Number of elements in an array.
// Space complexity: O(N), N = Number of elements in an array.

int subarryDivByK(vector<int> &nums, int k){
unordered_map<int, int> seenPrefixSumModK;
seenPrefixSumModK[0] = 1;
int subArrayCount = 0;
int prefixSum = 0;

for(auto &num: nums){
prefixSum += num;
while(prefixSum < 0) prefixSum += k;
int rem = prefixSum - k;
if(rem < 0) rem += k;
if(seenPrefixSumModK.count(prefixSum % k)){
subArrayCount += seenPrefixSumModK[prefixSum % k];
}
seenPrefixSumModK[prefixSum]++;
}

return subArrayCount;
}