mediumStack

Longest Unique Substring Solution

Problem Statement

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 the length of 3.
Example 2:
Input:s = "bbbbb"
Output:3
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.
Time: O(n) Space: O(min(n, m))
The optimal approach leverages a sliding window technique, utilizing a Set to track unique characters within the window, allowing for an efficient solution with a linear time complexity. By maintaining a window of unique characters and expanding or contracting it based on the presence of repeating characters, we can efficiently find the longest substring without repeating characters.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

function lengthOfLongestSubstring(s) { let chars = new Set(); let left = 0, result = 0; for (let right = 0; right < s.length; right++) { while (chars.has(s[right])) { chars.delete(s[left]); left++; } chars.add(s[right]); result = Math.max(result, right - left + 1); } return result; }