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

  • Coding Prep
    • GFG
      • GFG PTOD
    • Leetcode Problems
  • HLD
  • DS & Algo
  • Algo
  • Blind 75
  • Competitive Programming
  • Fast and Slow Pointer
  • GFG
  • GFG PTOD
  • Leetcode Problems
  • Leetcode PTOD
  • sliding window
  • fixed size sliding window
  • Variable size sliding window
  • DS
  • Leetcode Top Interview 150
  • General
  • Setup
  • Interview Questions
  • C++
  • Company Wise
  • Mastering in C programming (Crash Course)
  • Array in C
  • Programming
  • C Programming
  • C++
  • STL
  • C++-11
  • c++-14
  • Python
  • Roadmap
  • Setup
  • string in c
  • System Design
  • Design Pattern
  • Creational Design Patterns
  • Singleton
  • LLD
  • Low-level design
  • SOLID Principle
  • Top X
  • 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