Algorithm-Day08-Longest-Substring-Without-Repeating-Characters-lc-3

🧩 Problem Description

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

Example:

1
2
3
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

πŸ’‘ Brute Force (Too Slow)

Try all substrings and check if characters are unique.

  • Time: O(nΒ³)
  • Space: O(k) for checking duplicates

βœ… Correct but ❌ inefficient.


πŸ’‘ Optimized Approach: Sliding Window + HashMap

We use a sliding window with two pointers:

  • Expand right to include new characters
  • If a duplicate is found, move left to skip past the previous occurrence
  • Use a HashMap to store the last index of each character

πŸ”’ Java Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int maxLen = 0;
int left = 0;

for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);

if (map.containsKey(ch)) {
// Move left pointer past the previous occurrence of ch
left = Math.max(left, map.get(ch) + 1);
}

map.put(ch, right);
maxLen = Math.max(maxLen, right - left + 1);
}

return maxLen;
}
}

⏱ Time and Space Complexity

  • Time Complexity: O(n)
    Each character is visited at most twice.
  • Space Complexity: O(k)
    Where k is the number of unique characters (e.g. 26 for lowercase letters, 128 for ASCII)

✍️ Summary

  • Sliding window is ideal for β€œlongest substring” problems.
  • Key trick: update left pointer only when needed, and never move it backward.
  • Using a HashMap allows constant-time character index tracking.

This is one of the most popular sliding window problems β€” understanding this unlocks many similar challenges like Longest Subarray with Sum ≀ k, or Minimum Window Substring.