educative.io

A bit simpler code using different Map functions

There is a way to simplify map usage:

import java.util.*;

class LongestSubstringKDistinct {
  public static int findLength(String str, int k) {
    // TODO: Write your code here
    if (str == null || str.trim().isEmpty() || str.length() < k) {
      throw new IllegalArgumentException();
    }

    int maxLength = 0, windowStart = 0;

    Map<Character, Integer> frequencyMap = new HashMap<>();
    for (int windowEnd = 0; windowEnd < str.length(); windowEnd++) {
      frequencyMap.merge(str.charAt(windowEnd), 1, Integer::sum);
      while (frequencyMap.size() > k) {
        frequencyMap.compute(
          str.charAt(windowStart++), 
          (key, value) -> value-1 > 0 ? value-1 : null
        );
      }
      maxLength = Math.max(maxLength, windowEnd-windowStart+1);
    }
    return maxLength;
  }
}

The solution you provided is correct. We can use a different approach to solve a problem in most cases.