LeetCode

Longest Substring Without Repeating Characters

In this article we will learn about LeetCode Third question Longest Substring Without Repeating Characters in detail with optimized solution with Example.


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


Example 1:

Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.


Example 2:

Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.


Example 3:

Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.


Constraints:

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

Java Example

class Solution { public int lengthOfLongestSubstring(String s) { int l=0,r=0; Set<Character> seen = new HashSet(); int max=0; while(r< s.length()){ char c= s.charAt(r); if(seen.add(c)){ max= Math.max(max,r-l+1); r++; }else{ while(s.charAt(l)!=c){ seen.remove(s.charAt(l)); l++; } seen.remove(c); l++; } } return max; } } // 2023

Complexity :

Time complexity: O(N);
Space Complexity: O(1);


I hope you like this Amazing Longest Substring article.🙂


Also Read :

Admin

Share
Published by
Admin
Tags: DSA

Recent Posts

Blockchain Developer Roadmap

Blockchain is a shared, immutable ledger that facilitates the process of recording transactions and tracking assets…

4 weeks ago

Add Two Numbers

In this article we will learn about LeetCode Second question Add Two Numbers in detail with optimized…

7 months ago

Two Sum

LeetCode Questions -> 1. Two Sum In this article we will learn about LeetCode Two…

7 months ago

Web Designing Roadmap 2023

In this amazing Web Designing Roadmap 2023 article, we’ll learn about A to Z about…

11 months ago

Android Developer Roadmap 2023

Android developer -- In this amazing Android Developer Roadmap article, we’ll learn about A to…

1 year ago

Full-Stack Developer Roadmap 2023

The roadmap for a full stack developer can vary depending on the individual's goals and…

1 year ago