educative.io

My O(N + N) solution based on the previous problems but using a Set

class NoRepeatSubstring {

public static int findLength(String str) {

int windowStart = 0, maxLength = 0;

boolean hasElement = false;

Set<Character> uniqueCaharacters = new HashSet<>();

for(int windowEnd = 0; windowEnd < str.length(); windowEnd++){

  hasElement = !uniqueCaharacters.add(str.charAt(windowEnd));

  while(hasElement && windowStart < windowEnd){

    uniqueCaharacters.remove(str.charAt(windowStart));

    windowStart++;

  }

  maxLength = Math.max(maxLength, windowEnd - windowStart + 1);

}

return maxLength;

}

}

I also did it this way and i think it’s equivalent to the given solution but simpler.

However i don’t see how your specific code would work since “hasElement” doesn’t get updated inside the inner loop and would thus always close the window all the way.