3. Longest Substring Without Repeating Characters – Solution [Brute-Force to Best]

Here’s the question link on Leetcode 3. Longest Substring Without Repeating Characters:

https://leetcode.com/problems/longest-substring-without-repeating-characters/description

Brute Force: Generate Every Substring

The simplest approach is to generate every possible substring and check whether it contains duplicate characters.

We can use a set to keep track of the characters in the current substring.

  • Pick every starting index.
  • Keep extending the substring one character at a time.
  • If we find a character already in the set, stop extending.
  • Otherwise, add it to the set and update our answer.
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        int ans = 0;

        for(int i = 0; i < n; i++) {
            unordered_set<char> seen;

            for(int j = i; j < n; j++) {
                if(seen.count(s[j]))
                    break;

                seen.insert(s[j]);
                ans = max(ans, j - i + 1);
            }
        }

        return ans;
    }
};
3. Longest Substring Without Repeating Characters Brute Force

Optimal: Sliding Window + Hash Map O(n)

Instead of generating a new substring every time, let’s maintain a single window using two pointers: left and right.

The idea is simple:

  • Move right forward to expand the window.
  • If we encounter a repeating character, move left just past its previous occurrence.
  • Keep updating the maximum window length.

But how do we know where that character appeared previously?

We use a hash map to store the last index of every character.

Example

s = "abcabcbb"

We start with an empty window.

CharacterWindowActionMax Length
aaAdd a1
babAdd b2
cabcAdd c3
abcaMove left past previous a3
bcabMove left past previous b3
cabcMove left past previous c3
bcbMove left past previous b3
bbRemove duplicate3

The answer is 3.

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

        int left = 0;
        int ans = 0;

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

            char c = s[right];

            if(mp.find(c) != mp.end()) {
                left = max(left, mp[c] + 1);
            }

            mp[c] = right;

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

        return ans;
    }
};
3. Longest Substring Without Repeating Characters Optimal Solution

Leave a Reply