Longest Substring Without Repeating Characters

 Longest Substring Without Repeating Characters

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

Example:-

Input: s=abcabcbb

Output:3

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

SOURCE CODE:

function lengthOfLongestSubstring(s) {
  let maxLength = 0;
  let left = 0;
  const charIndexMap = {};

  for (let right = 0; right < s.length; right++) {
    const currentChar = s[right];

    if (charIndexMap[currentChar] !== undefined &&
charIndexMap[currentChar] >= left) {
      left = charIndexMap[currentChar] + 1;
    }

    charIndexMap[currentChar] = right;
    const currentLength = right - left + 1;
    maxLength = Math.max(maxLength, currentLength);
  }

  return maxLength;
}

// Test cases
console.log(lengthOfLongestSubstring("abcabcbb"));
// Output: 3
console.log(lengthOfLongestSubstring("bbbbb"));  
 // Output: 1
console.log(lengthOfLongestSubstring("pwwkew"));  
// Output: 3
JavaScript

👉2nd Largest from an array



Tausif

Hi! My name is Tausif Ahmad. I am a Full Stack Developer at Wipro and a Computer Science graduate from MANUU Hyderabad. I write exam-focused technical blogs and enjoy frontend development, blogging, and creative design.

Post a Comment (0)
Previous Post Next Post