Calculating the Length of the Longest Substring Without Repeating Characters

Given a string, identify the length of its longest contiguous substring containing no duplicate cahracters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The longest substring without repeating characters is "abc", which has a length of 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The longest substring is "b", with a length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", which has a length of 3. Note that "pwke" is a subsequence, not a substring.

An effective approach involves iterating through the string while tracking the start of the current candidate substring and the most recent positions of encountered characters. This method avoids a nested loop structure.

public static int FindLongestUniqueSubstring(string inputString)
{
    if (String.IsNullOrEmpty(inputString)) return 0;
    if (inputString.Length == 1) return 1;

    int maxSubstringLength = 0;
    int windowStartIndex = 0;
    Dictionary<char, int> charIndexMap = new Dictionary<char, int>();

    for (int windowEndIndex = 0; windowEndIndex < inputString.Length; windowEndIndex++)
    {
        char currentChar = inputString[windowEndIndex];
        
        if (charIndexMap.ContainsKey(currentChar))
        {
            windowStartIndex = Math.Max(charIndexMap[currentChar] + 1, windowStartIndex);
        }
        
        charIndexMap[currentChar] = windowEndIndex;
        maxSubstringLength = Math.Max(maxSubstringLength, windowEndIndex - windowStartIndex + 1);
    }
    return maxSubstringLength;
}

This implementation operates with a time complexity of O(n), where n is the length of the input string, as each character is processed once.

Tags: algorithms strings Sliding Window LeetCode C#

Posted on Thu, 07 May 2026 14:57:56 +0000 by rmbarnes82