Find the length of the longest substring that contains no repeated characters (e.g. "abcabcbb" -> 3, "abc").
Use a sliding window with two pointers and a map of each character's last index. Expand the right pointer; when a repeat is seen inside the window, jump the left pointer past the previous occurrence. Track the maximum window size. O(n).
public static int longestUnique(String s) {
Map<Character,Integer> last = new HashMap<>();
int start = 0, best = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (last.containsKey(c) && last.get(c) >= start) start = last.get(c) + 1;
last.put(c, i);
best = Math.max(best, i - start + 1);
}
return best;
}function longestUnique(s) {
const last = new Map();
let start = 0, best = 0;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (last.has(c) && last.get(c) >= start) start = last.get(c) + 1;
last.set(c, i);
best = Math.max(best, i - start + 1);
}
return best;
}def longest_unique(s):
last = {}
start = best = 0
for i, c in enumerate(s):
if c in last and last[c] >= start:
start = last[c] + 1
last[c] = i
best = max(best, i - start + 1)
return bestThe sliding-window technique is a workhorse for stream/log problems — longest clean run, rate windows, deduplicated spans.
When a repeat is found, a candidate resets start to i. Why can that give a wrong answer?