Tutorialspoint
Problem
Solution
Submissions

Longest Substring

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to find the length of the longest substring without repeating characters in a given string. A substring is a contiguous sequence of characters within a string.

Example 1
  • Input: s = "abcabcbb"
  • Output: 3
  • Explanation:
    • The answer is "abc", with the length of 3.
    • Step 1: Start with a sliding window at the beginning of the string.
    • Step 2: Expand the window to the right until we find a repeating character.
    • Step 3: When a repeating character is found, move the left boundary of the window.
    • Step 4: "abc" is the longest substring without repeating characters.
Example 2
  • Input: s = "bbbbb"
  • Output: 1
  • Explanation:
    • The answer is "b", with the length of 1.
    • Step 1: Initialize a sliding window.
    • Step 2: Since all characters are the same, the maximum length is 1.
    • Step 3: The longest substring without repeating characters is "b".
Constraints
  • 0 ≤ s.length ≤ 5 * 10^4
  • s consists of English letters, digits, symbols, and spaces.
  • Time Complexity: O(n)
  • Space Complexity: O(min(n, m)) where m is the size of the character set
StringsAirbnbSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a sliding window approach to keep track of the current substring
  • Maintain a hash set or dictionary to check for duplicate characters
  • When a duplicate is found, shrink the window from the left
  • Keep track of the maximum length seen so far

Steps to solve by this approach:

 Step 1: Initialize a HashSet to keep track of characters in the current window.
 Step 2: Use two pointers, left and right, to represent the sliding window.
 Step 3: Move the right pointer to expand the window until we find a duplicate character.
 Step 4: When a duplicate is found, move the left pointer and remove characters until the duplicate is removed.
 Step 5: Update the maximum length after each expansion of the window.
 Step 6: Continue this process until we reach the end of the string.
 Step 7: Return the maximum length found.

Submitted Code :