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 have completed B.Tech in Computer Science from Maulana Azad National Urdu University Hyderabad. I am always ready to have new experiences meet new people and learn new things. 1. I am very interested in Frontend Development. 2. I love video editing and graphics designing. 3. I enjoy challenges that enables to grow. 4. I am part time Blogger.

Post a Comment (0)
Previous Post Next Post