Longest Substring with At Most Two Distinct Characters
Given a string s
, return the length of the longest substring that contains at most two distinct characters.
Example 1:
Input: s = "eceba"
Output: 3
Explanation: The substring is "ece"
which its length is 3.
Example 2:
Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb"
which its length is 5.
Constraints:
1 <= s.length <= 105
s
consists of English letters.
Solution
Since we don't know the size of the window, we will apply the flexible sliding window template.
We will keep a last_occurrence
hashmap that stores the last occurence of a character in the current window.
Every time the right pointer reaches a new character, we update that character's last occurrence to r
.
In every iteration, we will check whether the current window is longer than max_len
.
This means that whenever the window becomes invalid, we must update the window first before the check.
We will update l
when condition(window)
evaluates to true
. Here, condition(window)
is when the hashmap contains three characters.
We must discard the entirety of one character c
, which means we will choose the smaller last_occurrence[c]
to maintain a longers substring.
So the new left pointer is updated to min(last_occurrence.values())+1
and we will delete this character from the last_occurrence
hashmap.
Implementation
def lengthOfLongestSubstringTwoDistinct(self, s):
last_occurrence = dict()
max_len, l = 0, 0
for r in range(len(s)):
last_occurrence[s[r]] = r
r += 1
if len(last_occurrence) == 3:
l = min(last_occurrence.values())+1
del last_occurrence[s[l-1]]
max_len = max(max_len, r - l)
return max_len
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorHow does merge sort divide the problem into subproblems?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!