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›Strings›Longest Substring Without Repeating Characters
MediumStrings

Longest Substring Without Repeating Characters

stringsliding-windowhash-map

Problem

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

Examples

Example 1

Input: s = "abcabcbb"

Output: 3

Explanation: "abc" is the longest.

Example 2

Input: s = "bbbbb"

Output: 1

Explanation: "b"

Example 3

Input: s = "pwwkew"

Output: 3

Explanation: "wke"

Constraints

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

Hints

Hint 1

Sliding window. Expand right; shrink left when a duplicate enters the window.

Solutions

public int lengthOfLongestSubstring(String s) {
    Map<Character, Integer> lastSeen = new HashMap<>();
    int maxLen = 0;
    int left = 0;
    for (int right = 0; right < s.length(); right++) {
        char c = s.charAt(right);
        // Shrink window from left if we've seen this char inside the window
        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(m,n)) where m=charset size