Back to LeetCode Series

LeetCode #3: Longest Substring Without Repeating Characters

Find the length of the longest substring with all unique characters using the sliding window technique.

Difficulty: MediumPattern: Sliding WindowTime: 7 min read

The Problem

Given a string s, find the length of the longest substringthat contains no repeated characters.

Examples

Input: "abcabcbb" → Output: 3 Longest: "abc"

Input: "bbbbb" → Output: 1 Longest: "b"

Input: "pwwkew" → Output: 3 Longest: "wke"

Input: "" → Output: 0 Longest: "(empty)"

Algorithm: Sliding Window

We use two pointers (left and right) to maintain a window of unique characters.

  • Expand the window by moving right
  • Use a Set to track seen characters
  • If a duplicate is found, shrink the window from the left until it’s unique again
  • Keep track of the maximum window size

How It Works: "abcabcbb"

Watch how the window slides and adjusts when duplicates are found:

Step 1: [a]bcabcbb → size=1
Step 2: [ab]cabcbb → size=2
Step 3: [abc]abcbb → size=3 ✅
Step 4: a[bc a]bcbb → 'a' repeated → shrink
Step 5: ab[cab]cbb → keep shrinking...
Final: Max length = 3 ("abc")

Solution (JavaScript)

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function lengthOfLongestSubstring(s) {
  const seen = new Set();
  let left = 0;
  let maxLength = 0;

  for (let right = 0; right < s.length; right++) {
    // Shrink window until no duplicate
    while (seen.has(s[right])) {
      seen.delete(s[left]);
      left++;
    }

    seen.add(s[right]);
    maxLength = Math.max(maxLength, right - left + 1);
  }

  return maxLength;
}

Complexity

  • Time: O(n) — each character visited at most twice
  • Space: O(min(m,n)) — m = charset size (e.g. 26 letters)

Understanding the Solution

Let‘s break down how this algorithm works — line by line — and why it’s so efficient.

What is a Set?

A Set is a built-in JavaScript object that stores unique values. You can add, delete, and check for values — all in O(1) average time.

js
1
2
3
4
5
6
const seen = new Set();

    seen.add('a');
    seen.has('a'); // → true
    seen.has('b'); // → false
    seen.delete('a');

In this problem, we use the Set to track which characters are currently in our window.

Why Use a Sliding Window?

We could check every substring (brute force), but that would be slow: O(n²).

Instead, we use a sliding window to explore substrings in real time:

  • Expand the window by moving the right pointer
  • Shrink it from the left when we see a duplicate
  • This ensures we only visit each character at most twice

Result: O(n) time — much faster!

Step-by-Step: "abcabcbb"

Start: left=0, right=0, seen="", maxLength=0
→ Add 'a' → seen=a, length=1
→ Add 'b' → seen=a,b, length=2
→ Add 'c' → seen=a,b,c, length=3 ✅
→ 'a' again! Duplicate → remove from left until 'a' is gone
→ Add new 'a' → window now "bca", length=3
... continue sliding ...
Key Insight: The window always contains unique characters. When we see a duplicate, we shrink from the left until it‘s gone.

❌ Brute Force (O(n²))

Check every possible substring:
For each start index, go through all end indices and check for duplicates.

Too slow for large strings!

✅ Sliding Window (O(n))

Use two pointers and a Set to maintain a valid window.
Each character is added and removed at most once.

Fast and scalable!

🔑 Why This Matters: The sliding window + hash set pattern is used everywhere: finding unique subarrays, detecting duplicates, parsing logs, and more. Mastering it gives you a powerful tool for algorithmic problem-solving.

🌍 Real-World Applications

This "sliding window + uniqueness" pattern appears in many real systems.

🔍 Text Analysis & Plagiarism Detection

Find the longest unique phrase in a document. Or detect when a writer starts repeating patterns — a sign of AI-generated or plagiarized content.

🔐 Security: Detecting Brute Force Attacks

Monitor login attempts. If a user tries many unique passwords quickly, it might be a bot. But if they repeat attempts, it‘s different. Tracking uniqueness over time uses similar logic.

📡 Networking: Packet Sequence Analysis

In TCP/IP, packets should arrive in order. If duplicates appear, it indicates retransmission. Sliding windows track unique packets over time to detect network issues.

🎮 Game Development: Combo Detection

In rhythm or puzzle games, you might want to detect the longest sequence of unique moves without repetition - exactly what this algorithm does.

💡 Fun Fact: This pattern is the foundation of substring search algorithms used in search engines, DNA sequence analysis, and even antivirus software.

Summary

The sliding window pattern is powerful for substring, subarray, and range queries. Two Sum uses "complement lookup", this one uses "window expansion + deduplication" — both are essential tools.

View All Challenges