educative.io

The solution can be coded more similar to previous question solution

Actually, the solution can be coded more similar to previous question solution and while condition can be while (matched == map.size()) instead of while (matched == pattern.length()). And no need to change from if (map.get(right) == 0) to (charFrequencyMap.get(rightChar) >= 0)

3 Likes

I know right? It’s very annoying how they keep changing solutions when the changes are not even necessary at all.

same here, got so confused on this part until i realized the while conditions were different from the previous. They should write that in the solution that this is another way to do it

Can someone explain while(matched == pattern.length()){} part with more clearity

Because in this solution they use a running count of all matching characters, instead of just qualifying keys in the map; this makes the count have to be equal the pattern length instead of the map length to start shrinking the window.

Insides the while loop, charFrequencyMap.get(leftChar) == 0 should also be >= to be consistent with the logic above when we increasing the matched counter:

if (charFrequencyMap.get(rightChar) >= 0) {
matched++;
}

However, matched == pattern.length() only when all values in the map are <= 0 so charFrequencyMap.get(leftChar) == 0 is sufficient to know when a matched character is going out of the window so as to decrease matched counter.

In short, I think we could have just reused the same solution using the map’s keys. Agreed with Tommy1,

They should write that in the solution that this is another way to do it

1 Like