Longest Substring with At Most Two Distinct Characters - Problem

Given a string s, return the length of the longest substring that contains at most two distinct characters.

A substring is a contiguous sequence of characters within a string. For example, in the string "abcdef", the substring "bcd" starts at index 1 and ends at index 3.

Example: For the string "eceba", the longest substring with at most two distinct characters is "ece" which has length 3.

Input & Output

Example 1 — Basic Case
$ Input: s = "eceba"
Output: 3
💡 Note: The longest substring with at most 2 distinct characters is "ece" with length 3
Example 2 — All Same Characters
$ Input: s = "aaaa"
Output: 4
💡 Note: The entire string has only 1 distinct character, so the answer is 4
Example 3 — Two Characters Mixed
$ Input: s = "abacbc"
Output: 4
💡 Note: The longest substring is "abac" or "acbc", both with 2 distinct characters and length 4

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of English letters

Visualization

Tap to expand
Longest Substring with At Most Two Distinct Characters INPUT String s = "eceba" e 0 c 1 e 2 b 3 a 4 Sliding Window Approach Window Hash Map Tracking char --> last_index 'e' --> 2 'c' --> 1 ALGORITHM STEPS 1 Initialize left=0, maxLen=0, hashMap={} 2 Expand Window Add char to hashMap 3 Shrink if needed If distinct > 2, move left 4 Update maxLen maxLen = max(maxLen, r-l+1) Iteration Trace i=0: {e:0} len=1 i=1: {e:0,c:1} len=2 i=2: {e:2,c:1} len=3 i=3: {e:2,b:3} len=2 i=4: {b:3,a:4} len=2 FINAL RESULT Longest Valid Substring: e c e b a "ece" contains 2 distinct chars Output 3 OK - Length = 3 Distinct characters in "ece": 'e' and 'c' (2 chars) Constraint: at most 2 Key Insight: Use a hash map to track the last index of each character. When we have more than 2 distinct characters, shrink the window from the left by removing the character with the smallest last index. Time Complexity: O(n) | Space Complexity: O(1) since map has at most 3 entries. TutorialsPoint - Longest Substring with At Most Two Distinct Characters | Hash Map Approach
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
78.4K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen