<aside> 💡 Sliding window, move right if hashmap doesn’t have letter, move left and delete if hashmap has letter.
</aside>
https://leetcode.com/problems/longest-substring-without-repeating-characters/
function lengthOfLongestSubstring(string) {
// ...
while (right < string.length) {
const currentLetter = string[right];
const leftLetter = string[left];
if (!map[currentLetter]) {
map[currentLetter] = 'literally anything';
right++;
} else {
left++;
delete map[leftLetter];
}
longest = Math.max(longest, right - left);
}
return longest;
}
<aside> 💡 First loop creates hashmap of letter occurrences. Second decreases the number of occurrences or deletes the letter from hashmap. Return true if hashmap is empty.
</aside>
https://leetcode.com/problems/valid-anagram/
function isAnagram(word1, word2) {
if (word1.length !== word2.length) {
return false;
}
const map = {};
for (let letter of word1) {
if (!map[letter]) {
map[letter] = 1;
} else {
map[letter]++;
}
}
for (let letter of word2) {
map[letter]--;
if (map[letter] === 0) {
delete map[letter];
}
}
return Object.keys(map).length === 0
}
<aside>
💡 When number changes is 2, the string AAABCD has longest substring CCCABD → CCCCCD is 5 characters long (length of window - max occured character = number of possible changes)
</aside>