Longest Substring Without Repeating Characters - JavaScript Solution with O(n) Time Complexity

Longest Substring Without Repeating Characters - JavaScript Solution with O(n) Time Complexity

Problem Definition

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

Input: A single string s.

Output: An integer representing the length of the longest substring without repeating characters.

Constraints:

Example:

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

Understanding the Problem

The core challenge of this problem is to find the longest substring in a given string that does not contain any repeating characters. This problem is significant in various applications such as text processing, data validation, and more. A common pitfall is to overlook the need for an efficient solution, especially given the constraint that the string length can be up to 50,000 characters.

Approach

To solve this problem, we need to consider different approaches:

Naive Solution

A naive solution would involve checking all possible substrings and determining if they contain repeating characters. This approach is not optimal due to its high time complexity of O(n3).

Optimized Solution

An optimized solution involves using a sliding window technique with a hash map to keep track of characters and their positions. This approach ensures that we only traverse the string once, resulting in a time complexity of O(n).

Algorithm

Here is a step-by-step breakdown of the optimized algorithm:

  1. Initialize a hash map to store the last seen index of each character.
  2. Use two pointers, left and right, to represent the current window of characters being considered.
  3. Iterate through the string with the right pointer.
  4. If the character at the right pointer is already in the hash map and its index is greater than or equal to left, move the left pointer to the right of the last seen index of that character.
  5. Update the hash map with the current index of the character.
  6. Calculate the length of the current window and update the maximum length if necessary.

Code Implementation

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    // Hash map to store the last seen index of each character
    let charIndexMap = new Map();
    // Initialize pointers and max length
    let left = 0, maxLength = 0;

    // Iterate through the string with the right pointer
    for (let right = 0; right < s.length; right++) {
        // If the character is already in the map and its index is within the current window
        if (charIndexMap.has(s[right]) && charIndexMap.get(s[right]) >= left) {
            // Move the left pointer to the right of the last seen index of the character
            left = charIndexMap.get(s[right]) + 1;
        }
        // Update the hash map with the current index of the character
        charIndexMap.set(s[right], right);
        // Calculate the length of the current window and update max length if necessary
        maxLength = Math.max(maxLength, right - left + 1);
    }

    return maxLength;
};

Complexity Analysis

The time complexity of the optimized solution is O(n) because we traverse the string once with the right pointer. The space complexity is O(min(n, m)), where n is the length of the string and m is the size of the character set.

Edge Cases

Consider the following edge cases:

Examples:

Input: s = ""
Output: 0

Input: s = "aaaaa"
Output: 1

Input: s = "abcdef"
Output: 6

Testing

To test the solution comprehensively, consider using a variety of test cases, including simple, complex, and edge cases. You can use testing frameworks like Jest or Mocha for automated testing.

Thinking and Problem-Solving Tips

When approaching such problems, consider the following tips:

Conclusion

In this blog post, we discussed how to solve the problem of finding the longest substring without repeating characters using an optimized approach with a sliding window technique. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for improving your coding skills and preparing for technical interviews.

Additional Resources

For further reading and practice, consider the following resources: