मुख्य कंटेंट तक स्किप करें

Longest Substring Without Repeating Characters

KANISHKA GUPTA
EditReport

Longest Substring Without Repeating Characters

Problem Statement

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

Video Explanation

Approach

We can use the sliding window technique along with a hash map to track the characters and their indices.

Steps:

  1. Initialize:

    • Create a hash map to store the last seen index of each character.
    • Initialize two pointers, start and end, to the beginning of the string.
  2. Iterate:

    • For each character, check if it has been seen and is in the current window.
    • Update the start pointer if necessary.
    • Update the end.
  3. Return:

    • Return the maximum length found.

Solutions

class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> charMap;
int left = 0, maxLen = 0;
for (int right = 0; right < s.length(); right++) {
if (charMap.count(s[right]) && charMap[s[right]] >= left) {
left = charMap[s[right]] + 1;
}
charMap[s[right]] = right;
maxLen = max(maxLen, right - left + 1);
}
return maxLen;
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Longest Substring Without Repeating Characters"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.