educative.io

Educative

Why use a hashmap in the explanation when a hashet solution is simpler?

Why use the hashmap with for and while loops, when you can use a hashset with if/else inside the for loop?

class LongestSubstringKDistinct {
public static int findLength(String str, int k) {
  Set<Character> l = new HashSet<Character>();
  int start = 0;
  int max = 0;
  char[] chars = str.toCharArray();
  for(int end = 0; end < chars.length; end++) {
    l.add(chars[end]);
    if(l.size() <= k) {
      max = Math.max(max, end - start +1);
    } else {
      l.remove(chars[start]);
      start++;
    }
  }
  return max;
}
}

Is it because say that there are two letter "a"s in the sliding window, and you remove the leftmost letter (which is “a”) from the HashSet, no letter “a” will be included in the HashSet, while there’s still an “a” in the sliding window, which will cause a collision of the number of different characters in the sliding window?

2 Likes