Skip to content

Instantly share code, notes, and snippets.

@flacial
Created November 16, 2022 18:47
Show Gist options
  • Save flacial/c8798eb6df1d86603cc08731a4fd0871 to your computer and use it in GitHub Desktop.
Save flacial/c8798eb6df1d86603cc08731a4fd0871 to your computer and use it in GitHub Desktop.
Sliding Window: longest substring with same letters
/*
Steps:
1. We'll iterate through the array
2. We'll create a hashmap to remember the occurence for each char
3. We'll also remember the most repeated char in the sliding window
4. If we removed the most repeated char from the sliding window and the left chars to replace with the most repeated char is more than K, we'll shrink the window
5. We'll remember the length of the sliding window as the one with the longest substring with the same letter
*/
const longestSubstringWithSameLetters = (arr, K) => {
let windowStart = 0,
maxLength = 0,
mostRepeatedChar = 0,
hashMap = {};
for (let windowEnd = 0; windowEnd < arr.length; windowEnd++) {
const rightChar = arr[windowEnd]
// Remember the char occurrence
hashMap[rightChar] = (hashMap[rightChar] || 0) + 1
// Remeber the most repeated character in the current sliding window
mostRepeatedChar = Math.max(mostRepeatedChar, hashMap[rightChar])
// If after removing the most repeated chars from the sliding window,
// the count of the chars to be replaced with the char of the most
// repeated char is more than K, slide the first element out
// E.g, in `aabcc` the most repeated char is `a`
// After removing `a`, we get `bcc`. `bcc` is greater than K
// if `k` is 2. So, we shrink the window now
if ((windowEnd - windowStart + 1 - mostRepeatedChar) > K) {
// We could remove the character from hasMap but it didn't
// change the output to me
// hashMap[arr[windowStart]] -= 1
windowStart += 1
}
// Set the longest substring by comparing the current window size to the
// previous window size
maxLength = Math.max(maxLength, windowEnd - windowStart + 1)
}
return maxLength
};
longestSubstringWithSameLetters('aabccbb', 2) // 5
longestSubstringWithSameLetters('abbcb', 1) // 4
longestSubstringWithSameLetters('abccde', 1) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment