Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Two Pointers & Sliding Window›Longest Substring Without Repeating Characters
MediumTwo Pointers & Sliding Window

Longest Substring Without Repeating Characters

sliding-windowhash-mapstring

Problem

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

Examples

Example 1

Input: s = "abcabcbb"

Output: 3

Explanation: The answer is "abc", with length 3.

Example 2

Input: s = "bbbbb"

Output: 1

Explanation: The answer is "b", with length 1.

Example 3

Input: s = "pwwkew"

Output: 3

Explanation: The answer is "wke", with length 3. Note "pwke" is a subsequence, not a substring.

Constraints

  • •0 <= s.length <= 5 * 10^4
  • •s consists of English letters, digits, symbols and spaces

Hints

Hint 1

Think in terms of a window [left, right] that only ever grows or shrinks from one side.

Hint 2

What data structure lets you check 'have I seen this character in my current window' in O(1)?

Hint 3

When you hit a repeat, you don't need to shrink one character at a time — jump left directly past the previous occurrence.

Solutions

public int lengthOfLongestSubstring(String s) {
    Map<Character, Integer> lastSeen = new HashMap<>();
    int maxLen = 0, left = 0;
    for (int right = 0; right < s.length(); right++) {
        char c = s.charAt(right);
        if (lastSeen.containsKey(c) && lastSeen.get(c) >= left) {
            left = lastSeen.get(c) + 1;
        }
        lastSeen.put(c, right);
        maxLen = Math.max(maxLen, right - left + 1);
    }
    return maxLen;
}
Java

Time: O(n) · Space: O(min(n, charset size))