← Back to libraryQuestion 63 of 273
⌨️Java CodingAdvanced

Longest Substring Without Repeating Characters

📌 Definition:

Find the length of the longest substring that contains no repeated characters (e.g. "abcabcbb" -> 3, "abc").

📖 Detailed Explanation:

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).

💻 Solutions:
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 best
🔑 Key Points:
  • Sliding window + last-seen index map
  • Move left past the previous occurrence, never backward
  • Track max length as the window grows
  • O(n) time, O(k) space
🌍 Real-World Example:

The sliding-window technique is a workhorse for stream/log problems — longest clean run, rate windows, deduplicated spans.

🎯 Scenario-Based Interview Question:

When a repeat is found, a candidate resets start to i. Why can that give a wrong answer?