My App
Dsa

Longest Substring Without Repeating Characters

A simple explanation and clean Python solution for this Blind 75 problem.

🧩 Longest Substring Without Repeating Characters

You are given a string.
Find the longest part (substring) that has no repeating characters.


πŸ”’ Example

Input:


"abcabcbb"
SubstringHas repeats?Length
abcβœ… unique3
abca❌ repeats-
bcaβœ… unique3

βœ… Longest substring = "abc"
Answer = 3


πŸ’‘ Real-World Example

Imagine typing a password and checking the longest part without repeated letters,
since repeating ones make it weak.

Or in music, you might check the longest streak of non-repeating notes 🎡.


βš™οΈ Approaches

πŸ₯‡ Approach 1: Brute Force

Try all substrings and check if all characters are unique.

def longestSubstring(s):
    longest = 0
    for i in range(len(s)):
        for j in range(i, len(s)):
            part = s[i:j+1]
            if len(set(part)) == len(part):  # all unique
                longest = max(longest, len(part))
    return longest

⏱ Time: O(nΒ²) πŸ“¦ Space: O(n)

βœ… Easy to understand ❌ Slow for big strings


πŸ₯ˆ Approach 2: Sliding Window (Efficient βœ…)

Use two pointers β€” left and right. Expand right, shrink left when duplicates appear.

def longestSubstring(s):
    seen = set()
    left = 0
    longest = 0

    for right in range(len(s)):
        while s[right] in seen:
            seen.remove(s[left])
            left += 1
        seen.add(s[right])
        longest = max(longest, right - left + 1)
    return longest

⏱ Time: O(n) πŸ“¦ Space: O(n)

βœ… Fast and simple for large input βœ… Common interview pattern


πŸ₯‰ Approach 3: Using Dictionary (Index Map)

Keep track of the last seen index for each character.

def longestSubstring(s):
    seen = {}
    left = 0
    longest = 0

    for right, char in enumerate(s):
        if char in seen and seen[char] >= left:
            left = seen[char] + 1
        seen[char] = right
        longest = max(longest, right - left + 1)
    return longest

⏱ Time: O(n) πŸ“¦ Space: O(n)

βœ… Cleanest version βœ… Most preferred for interviews


🧠 Real-Life Uses

Use CaseExample
πŸ”‘ Password StrengthCheck longest non-repeating characters
πŸ“± Text AnalysisFind unique letter streaks in input
πŸ•Ή Game LogicLongest unique sequence of moves
πŸ’¬ Chat AppsDetect longest non-repeated pattern

⚠️ Drawbacks

DrawbackExplanation
πŸ•’ Brute Force is slowChecks every substring
πŸ’Ύ Uses memorySet/dict store characters
🧩 Works only on charactersModify to support words

πŸ” Example Dry Run

Input: "pwwkew"

StepLeftRightWindowLongest
000"p"1
101"pw"2
202"pww" β†’ ❌ duplicate2
313"wk"2
414"wke"3 βœ…
515"wkew" β†’ ❌ duplicate3

βœ… Final Answer = 3 ("wke")


🧾 Summary Table

ApproachLogicTimeSpaceNotes
Brute ForceTry all substringsO(nΒ²)O(n)Simple but slow
Sliding Window (Set)Move window & remove duplicatesO(n)O(n)Best balance
Index Map (Dict)Track last seen indexO(n)O(n)Fastest βœ…

πŸ’‘ Key Takeaways

  • Use sliding window for β€œlongest substring” or β€œsubarray” problems.
  • Use a set or dictionary to track duplicates.
  • Practice dry runs to understand window movement.

✨ Real-World Analogy

Imagine walking on tiles labeled with letters:

A - B - C - A - B - C - B - B

You keep walking until you step on a tile you’ve already seen. Then, step back and start again. The farthest you go without repeating = your answer.


🏁 Final Thought

This problem helps you understand:

  • Sliding Window Technique πŸšͺ
  • HashSets & HashMaps πŸ’Ύ
  • Thinking in β€œexpand & shrink” windows

Once you learn this, you can easily move to:

  • Longest Subarray with Sum K
  • Longest Substring with at most K distinct characters
  • Minimum Window Substring

---
Longest Substring Without Repeating Characters