Longest Substring Without Repeating Characters
Longest Substring Without Repeating Characters asks for the maximum length of a contiguous substring containing unique characters only. As you scan the string, duplicates force the valid window to shift forward. The task is to track the longest unique window length, not the substring content itself.
The standard linear solution uses a sliding window with a map of last seen indices. Move the right pointer through the string; when the current character was seen inside the active window, move left boundary to one position after that previous index. Update the last-seen index and record the best window size after each step.
Judge includes repeated-character runs, alternating repeat patterns, empty strings, and mixed cases where the best window appears in the middle. Return one integer length. Correctness depends on never moving the left boundary backward and handling duplicate hits relative to current window start. With those rules, the algorithm runs in O(n) time and remains stable for long strings with heavy repetition.
When duplicates appear, only move the left boundary if the previous occurrence is inside the current window; older occurrences outside the window should be ignored. This condition prevents accidental over-shrinking and is the difference between correct O(n) behavior and subtle length underestimation.
Examples
Longest unique substring is "abc".
Longest unique substring is "b".
Longest unique substring is "wke".
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int longest_substring_without_repeating_characters(String s) {
Map<Character, Integer> last = new HashMap<>();
int left = 0, ans = 0;
for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);
if (last.containsKey(ch) && last.get(ch) >= left) {
left = last.get(ch) + 1;
}
last.put(ch, right);
ans = Math.max(ans, right - left + 1);
}
return ans;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
