Skip to content
  • Home
  • YouTube
  • About
  • Contact
Learn to Code and Code to Learn

Learn to Code and Code to Learn

Your Journey to Code Mastery

  • General
    • Setup
    • Mastering in C programming (Crash Course)
  • DSA Patterns
    • Fast and Slow Pointer
    • sliding window
      • fixed size sliding window
      • Variable size sliding window
  • Coding Prep
    • Leetcode Problems
      • DS & Algo
      • Blind 75
      • Leetcode PTOD
      • Leetcode Top Interview 150
    • GFG
      • GFG PTOD
  • Programming
    • C Programming
    • C++
      • C++-11
      • c++-14
      • STL
    • Python
  • HLD
  • LLD
    • SOLID Principle
    • Design Pattern
      • Creational Design Patterns
        • Singleton
  • Company wise Interview Questions
    • Google
    • Microsoft
  • Toggle search form

3. Longest Substring Without Repeating Characters

Problem:
Given a string s, find the length of the longest substring without repeating characters.

Example:

Input:  "abcabcbb"
Output: 3
Explanation: "abc"

🔥 Best Approach (HashMap Jump Optimization)

Instead of removing one by one,
jump left directly to the correct position.

⚙️ Algorithm

Use hashmap<char, last_index>

For each character:
if already seen inside current window:
move left = last_index + 1

update answer
update last seen index

💻 C++ Optimal Solution

class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> lastSeen;

int left = 0;
int ans = 0;

for (int right = 0; right < s.size(); right++) {

char ch = s[right];

// duplicate inside current window
if (lastSeen.count(ch)) {
left = max(left, lastSeen[ch] + 1);
}

lastSeen[ch] = right;

ans = max(ans, right - left + 1);
}

return ans;
}
};

🔍 Dry Run

Input:

"abcabcbb"
rightcharleftwindowans
0a0a1
1b0ab2
2c0abc3
3a1bca3
4b2cab3
5c3abc3
6b5cb3
7b7b3

⏱️ Complexity

Optimal

  • Time: O(n)
  • Space: O(charset)

Because:

  • Each character processed once
  • left never moves backward

Copyright © 2026 Learn to Code and Code to Learn.

Powered by PressBook Blog WordPress theme