bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 159. Longest Substring with At Most Two Distinct Characters

159. Longest Substring with At Most Two Distinct Characters

Leetcode Solutions

Sliding Window Approach

  1. If the string length N is smaller than 3, return N.
  2. Initialize two pointers left = 0 and right = 0 and max_len = 2.
  3. Use a hashmap to keep track of characters and their rightmost positions within the window.
  4. Iterate with the right pointer over the string:
    • If the hashmap contains less than 3 distinct characters, add the current character s[right] to the hashmap and move right pointer to the right.
    • If the hashmap contains 3 distinct characters, remove the leftmost character from the hashmap and move the left pointer to exclude this character from the window.
    • Update max_len with the maximum of its current value and the length of the current window.
  5. Return max_len as the result.
UML Thumbnail

Two Pointers with Character Count

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...