Sample Problem: Longest Substring Without Repeating Characters.
Given a string s, find the length of the longest substring without repeating characters.
T/S: O(n)/O(a), where n = s.length, a = size of character set
public int lengthOfLongestSubstring(String s) {
var n = s.length();
if (n < 2)
return n;
var left = 0;
var right = 0;
var maxLength = 0;
var map = new HashMap<Character, Integer>(); // map of char to its latest index
while (right < n) {
var ch = s.charAt(right);
if (map.containsKey(ch)) {
maxLength = Math.max(maxLength, right - left); // record max window size
left = Math.max(left, map.get(ch) + 1); // shrink window from left
}
map.put(ch, right);
right++ // expand window to the right
}
return Math.max(maxLength, right - left);
}A slight variation using the template for Sliding Window that can be used in the following problems that follow a similar pattern:
Fix Sized Window
Variable Sized Window
Legend: P = Premium
Comments and contributions for improvement are appreciated. Thanks!