How to find the length of the longest substring from the given string without repeating the characters using C#?

The longest substring without repeating characters problem can be efficiently solved using the sliding window technique with two pointers. This approach maintains a window of unique characters and expands or contracts it based on whether duplicates are found.

Algorithm Overview

The sliding window technique uses two pointers i (left) and j (right) to maintain a window of unique characters. When a duplicate character is encountered, the left pointer moves forward to exclude the duplicate, while the right pointer continues expanding the window.

Sliding Window Technique String: a b c a b c i j Current Window: "abc" Steps: 1. Expand window with unique chars 2. When duplicate found, shrink from left

Syntax

The basic structure uses a HashSet to track characters in the current window −

HashSet<char> window = new HashSet<char>();
int left = 0, maxLength = 0;

for (int right = 0; right < s.Length; right++) {
    while (window.Contains(s[right])) {
        window.Remove(s[left]);
        left++;
    }
    window.Add(s[right]);
    maxLength = Math.Max(maxLength, window.Count);
}

Using HashSet for Optimal Performance

A HashSet provides O(1) lookup time for checking duplicates, making it more efficient than a List for this problem −

using System;
using System.Collections.Generic;

public class Solution {
    public int LengthOfLongestSubstring(string s) {
        HashSet<char> window = new HashSet<char>();
        int left = 0;
        int maxLength = 0;
        
        for (int right = 0; right < s.Length; right++) {
            while (window.Contains(s[right])) {
                window.Remove(s[left]);
                left++;
            }
            window.Add(s[right]);
            maxLength = Math.Max(maxLength, window.Count);
        }
        
        return maxLength;
    }
}

public class Program {
    public static void Main(string[] args) {
        Solution solution = new Solution();
        
        string test1 = "abcabcbb";
        int result1 = solution.LengthOfLongestSubstring(test1);
        Console.WriteLine($"Input: "{test1}" ? Output: {result1}");
        
        string test2 = "bbbbb";
        int result2 = solution.LengthOfLongestSubstring(test2);
        Console.WriteLine($"Input: "{test2}" ? Output: {result2}");
        
        string test3 = "pwwkew";
        int result3 = solution.LengthOfLongestSubstring(test3);
        Console.WriteLine($"Input: "{test3}" ? Output: {result3}");
    }
}

The output of the above code is −

Input: "abcabcbb" ? Output: 3
Input: "bbbbb" ? Output: 1
Input: "pwwkew" ? Output: 3

Using Dictionary for Index Tracking

An alternative approach uses a Dictionary to store the last seen index of each character, allowing for more efficient window adjustments −

using System;
using System.Collections.Generic;

public class OptimizedSolution {
    public int LengthOfLongestSubstring(string s) {
        Dictionary<char, int> charIndex = new Dictionary<char, int>();
        int left = 0;
        int maxLength = 0;
        
        for (int right = 0; right < s.Length; right++) {
            if (charIndex.ContainsKey(s[right]) && charIndex[s[right]] >= left) {
                left = charIndex[s[right]] + 1;
            }
            charIndex[s[right]] = right;
            maxLength = Math.Max(maxLength, right - left + 1);
        }
        
        return maxLength;
    }
}

public class Program {
    public static void Main(string[] args) {
        OptimizedSolution solution = new OptimizedSolution();
        
        string[] testCases = {"abcabcbb", "bbbbb", "pwwkew", "dvdf"};
        
        foreach (string test in testCases) {
            int result = solution.LengthOfLongestSubstring(test);
            Console.WriteLine($"Input: "{test}" ? Length: {result}");
        }
    }
}

The output of the above code is −

Input: "abcabcbb" ? Length: 3
Input: "bbbbb" ? Length: 1
Input: "pwwkew" ? Length: 3
Input: "dvdf" ? Length: 3

Comparison of Approaches

Approach Data Structure Time Complexity Space Complexity
HashSet Method HashSet<char> O(2n) = O(n) O(min(m,n))
Dictionary Method Dictionary<char,int> O(n) O(min(m,n))

Note: m represents the character set size (e.g., 128 for ASCII), and n represents the string length.

Conclusion

The sliding window technique efficiently solves the longest substring without repeating characters problem in O(n) time. The HashSet approach is straightforward and intuitive, while the Dictionary approach provides optimal performance by avoiding unnecessary character removals during window adjustments.

Updated on: 2026-03-17T07:04:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements